<?php namespace App\Http\Controllers\Services;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use Validator, Input, Redirect ; 
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

use Config;


/**
 * API Endpoint: POST /api/reset-password
 *
 * Deskripsi: Reset password user.
 *
 * Parameter POST:
 *   - id           (string)   : User ID (nomor telepon)
 *   - new_password (string)   : Password baru (min 6 karakter)
 *
 * Response sukses:
 *   {
 *     "success": true,
 *     "message": "Password berhasil direset"
 *   }
 *
 * Response gagal:
 *   {
 *     "success": false,
 *     "message": "..."
 *   }
 *
 * Contoh request:
 *   POST /api/reset-password
 *   Body: { "id": "08123456789", "new_password": "passwordbaru" }
 */
class PicaController extends Controller {

	public function __construct()
	{		
		parent::__construct();
        
	}

	public function index( Request $request )
	{
	}	

public function getDataKuadranCashcostPanen(Request $request)
{
    try {
        // ── 1. Parse parameter ─────────────────────────────────────────────

        $body = file_get_contents('php://input');
		$jsonparse = json_decode($body);
        $cluster   = $jsonparse->cluster ?? null;
        $dateParam = $jsonparse->date ?? null;

        if (!$dateParam) {
            return response()->json([
            'sts'  => 'error',
            'msg'  => "Parameter 'date' wajib diisi dalam format YYYY-MM-DD. Contoh: 2026-04-01.",
            'data' => null,
            ]);
        }

        $dt = \DateTime::createFromFormat('Y-m-d', $dateParam);
        if (!$dt) {
            return response()->json([
            'sts'  => 'error',
            'msg'  => "Parameter 'date' harus dalam format YYYY-MM-DD. Contoh: 2026-04-01.",
            'data' => null,
            ]);
        }


        $tahun = (int) $dt->format('Y');
        $bulan = (int) $dt->format('n');

        // ── 2. Konstanta kuadran ───────────────────────────────────────────
        $x_threshold = 2.5;    // Nilai PICA (sumbu x)
        $y_threshold = 8500;   // Cash Cost tengah (sumbu y, polarity negative)
        $x_offset    = 0.5;
        $y_offset    = 500;
        $y_min       = 0;
        $y_max       = 25000;
        $x_min       = 0;
        $x_max       = 5;

        // Definisi kategori
        $cat_hijau  = [
            'id'              => 1,
            'nama_kategori'   => 'Hijau',
            'slug'            => 'hijau',
            'warna'           => '#05ed00',
            'warna_secondary' => '#018a00',
            'warna_text'      => '#ffffff',
            'desc'            => 'PICA baik, Cash Cost rendah (terbaik)',
        ];
        $cat_oranye = [
            'id'              => 2,
            'nama_kategori'   => 'Oranye',
            'slug'            => 'oranye',
            'warna'           => '#ed9d00',
            'warna_secondary' => '#d4a200',
            'warna_text'      => '#1a1a1a',
            'desc'            => 'PICA baik, Cash Cost tinggi',
        ];
        $cat_kuning = [
            'id'              => 3,
            'nama_kategori'   => 'Kuning',
            'slug'            => 'kuning',
            'warna'           => '#eded00',
            'warna_secondary' => '#8a8a00',
            'warna_text'      => '#1a1a1a',
            'desc'            => 'PICA buruk, Cash Cost rendah',
        ];
        $cat_merah  = [
            'id'              => 4,
            'nama_kategori'   => 'Merah',
            'slug'            => 'merah',
            'warna'           => '#ed0000',
            'warna_secondary' => '#8a0000',
            'warna_text'      => '#ffffff',
            'desc'            => 'PICA buruk, Cash Cost tinggi (terburuk)',
        ];

        // Urutan slug untuk historical (best → worst), harus sama setiap bulan
        $slug_order = ['hijau', 'kuning', 'oranye', 'merah'];
        $cat_map    = [
            'hijau'  => $cat_hijau,
            'kuning' => $cat_kuning,
            'oranye' => $cat_oranye,
            'merah'  => $cat_merah,
        ];

        // ── 3. Helper: klasifikasi satu baris ke slug kuadran ─────────────
        $classify = function ($nilai_pica, $real_cashcost)
            use ($x_threshold, $y_threshold) {
            $good_x = ($nilai_pica  >= $x_threshold);
            $good_y = ($real_cashcost <  $y_threshold); // polarity negative: rendah = baik
            if ($good_x && $good_y)  return 'hijau';
            if ($good_x && !$good_y) return 'oranye';
            if (!$good_x && $good_y) return 'kuning';
            return 'merah';
        };

        // ── 4. Helper: format periode ──────────────────────────────────────
        $makePeriod = function (int $y, int $m) {
            $last = cal_days_in_month(CAL_GREGORIAN, $m, $y);
            $pad  = str_pad($m, 2, '0', STR_PAD_LEFT);
            return [
                'start'       => "{$y}-{$pad}-01T00:00:00+07:00",
                'end'         => "{$y}-{$pad}-{$last}T00:00:00+07:00",
                'start_plain' => "{$y}-{$pad}-01",
                'end_plain'   => "{$y}-{$pad}-{$last}",
            ];
        };

        // ── 5. Data bulan ini untuk section ───────────────────────────────
        $results = \DB::select('CALL sp_cashcost_panen(?, ?)', [$cluster, $bulan]);
        $period  = $makePeriod($tahun, $bulan);

        $points = [];

        foreach ($results as $index => $row) {
            $nilai_pica   = isset($row->nilai_pica)   ? (float) $row->nilai_pica   : 0.0;
            $real_cashcost = isset($row->real_cashcost) ? (float) $row->real_cashcost : 0.0;
            $kode_kebun   = $row->kode_kebun ?? ('K' . ($index + 1));
            $nama_kebun   = $row->nama_kebun ?? $row->nama_cluster ?? '';

            $points[] = [
                'x'                  => $nilai_pica,
                'y'                  => $real_cashcost,
                'region'             => $nama_kebun,
                'outputType'         => 'Cash Cost vs. Nilai PICA (Masa Panen)',
                'periode_start'      => $period['start'],
                'periode_end'        => $period['end'],
                'kode_pabrik'        => $kode_kebun,
                'parameter_id'       => $index + 1,
                'parameter_slug'     => 'cashcost_vs_pica',
                'parameter_nickname' => 'Cash Cost',
            ];
        }

        // 4 placeholder sudut domain chart (wajib ada persis 4)
        $ph_corners = [
            ['x' => $x_min,       'y' => $y_min],
            ['x' => $x_min,       'y' => $y_max],
            ['x' => $x_max,       'y' => $y_min],
            ['x' => $x_max,       'y' => $y_max],
        ];
        foreach ($ph_corners as $ph) {
            $points[] = [
                'x'                  => $ph['x'],
                'y'                  => $ph['y'],
                'region'             => '',
                'outputType'         => 'Placeholder',
                'periode_start'      => $period['start_plain'],
                'periode_end'        => $period['end_plain'],
                'kode_pabrik'        => 'placeholder',
                'parameter_id'       => 0,
                'parameter_slug'     => 'cashcost_vs_pica',
                'parameter_nickname' => 'Cash Cost',
            ];
        }

        // ── 6. Bangun sections ─────────────────────────────────────────────
        $sections = [
            [
                'id'    => 'cashcost_vs_pica',
                'label' => 'Cash Cost',
                'icon'  => 'CircleDollarSign',
                'title' => 'Cash Cost vs. Nilai PICA (Masa Panen)',
                'x_axis' => 'Nilai PICA',
                'y_axis' => 'Real Cash Cost',
                'data'  => [
                    'rule' => [
                        'x_threshold' => $x_threshold,
                        'y_threshold' => $y_threshold,
                        'x_offset'    => $x_offset,
                        'y_offset'    => $y_offset,
                        'polarity'    => 'negative',
                        // Q1 top-right setelah flip y = PICA baik + cashcost rendah = hijau
                        'color_q1'    => $cat_hijau,
                        // Q2 top-left = PICA buruk + cashcost rendah = kuning
                        'color_q2'    => $cat_kuning,
                        // Q3 bottom-left = PICA buruk + cashcost tinggi = merah (terburuk)
                        'color_q3'    => $cat_merah,
                        // Q4 bottom-right = PICA baik + cashcost tinggi = oranye
                        'color_q4'    => $cat_oranye,
                        'desc'        => 'Kuadran Cash Cost vs Nilai PICA Masa Panen. '
                                       . 'Sumbu X = Nilai PICA (threshold 2.5), '
                                       . 'Sumbu Y = Real Cash Cost (threshold Rp 8.500, lower is better).',
                    ],
                    'data' => $points,
                ],
            ],
        ];

        // ── 7. Bangun historical (6 bulan terakhir termasuk bulan ini) ─────
        $historical = [];

        for ($i = 5; $i >= 0; $i--) {
            $hist_dt    = clone $dt;
            $hist_dt->modify("-{$i} month");
            $hist_bulan = (int) $hist_dt->format('n');
            $hist_tahun = (int) $hist_dt->format('Y');
            $date_label = $hist_dt->format('M Y'); // "Apr 2026"

            $hist_results = \DB::select('CALL sp_cashcost_panen(?, ?)', [$cluster, $hist_bulan]);

            // Kumpulkan kode_kebun per kategori
            $buckets_raw = ['hijau' => [], 'kuning' => [], 'oranye' => [], 'merah' => []];

            foreach ($hist_results as $row) {
                $np  = isset($row->nilai_pica)    ? (float) $row->nilai_pica    : 0.0;
                $rc  = isset($row->real_cashcost)  ? (float) $row->real_cashcost  : 0.0;
                $kode = trim($row->kode_kebun ?? '');

                // Lewati baris tanpa kode atau tanpa data
                if ($kode === '' || ($np == 0.0 && $rc == 0.0)) {
                    continue;
                }

                $slug = $classify($np, $rc);
                $buckets_raw[$slug][] = $kode;
            }

            // Format bucket sesuai spesifikasi
            $data_buckets = [];
            foreach ($slug_order as $slug) {
                $colors  = $cat_map[$slug];
                $ids_arr = $buckets_raw[$slug];

                if (empty($ids_arr)) {
                    // Zero records → data harus array kosong []
                    $data_buckets[] = [
                        'slug'            => $slug,
                        'warna'           => $colors['warna'],
                        'warna_secondary' => $colors['warna_secondary'],
                        'warna_text'      => $colors['warna_text'],
                        'data'            => [],
                    ];
                } else {
                    // Ada record → data adalah object SectionCountMap
                    $ids_str = implode(',', $ids_arr);
                    $data_buckets[] = [
                        'slug'            => $slug,
                        'warna'           => $colors['warna'],
                        'warna_secondary' => $colors['warna_secondary'],
                        'warna_text'      => $colors['warna_text'],
                        'data'            => [
                            'cashcost_vs_pica' => [
                                'ids'   => $ids_str,
                                'count' => count($ids_arr),
                            ],
                        ],
                    ];
                }
            }

            $historical[] = [
                'date' => $date_label,
                'data' => $data_buckets,
            ];
        }

        // ── 8. Return envelope ─────────────────────────────────────────────
        return response()->json([
            'sts'  => 'success',
            'msg'  => 'OK',
            'data' => [
                'sections'   => $sections,
                'historical' => $historical,
            ],
        ]);

    } catch (\Exception $e) {
        return response()->json([
            'sts'  => 'error',
            'msg'  => $e->getMessage(),
            'data' => null,
        ]);
    }
}


}