<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Models\Sample;
use App\Models\Brand;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
// use App\Models\Bulan;
// use App\Models\Minggu;

class SampleController extends Controller
{
    // public function index(Request $request)
    // {
    //     // Ambil semua brand untuk select option di view
    //     $brands = Brand::all();

    //     // Ambil brand yang dipilih dari query parameter, default ke brand pertama jika tidak ada
    //     $brand = $request->get('brand', $brands->first()->id ?? 1);

    //     // Ambil data sample berdasarkan brand yang dipilih dan group by bulan
    //     $samples = Sample::where('brand', $brand)->get()->groupBy('bulan');

    //     // Inisialisasi array untuk menampung hasil akhir
    //     $data = [];
    //     $hasData = false;

    //     // Loop bulan dari 1 sampai 12
    //     foreach (range(1, 12) as $bulan) {
    //         $mingguData = [];

    //         if (isset($samples[$bulan])) {
    //             for ($minggu = 1; $minggu <= 4; $minggu++) {
    //                 $item = $samples[$bulan]->firstWhere('minggu', $minggu);
    //                 $mingguData[] = $item ? $item->data : null;
    //             }

    //             $data[] = [
    //                 'bulan' => $this->getNamaBulan($bulan),
    //                 'minggu' => $mingguData,
    //             ];

    //             $hasData = true;
    //         }
    //     }

    //     // Kirim data ke view
    //     return view('sample', compact('data', 'brand', 'hasData', 'brands'));
    // }

    public function index(Request $request)
    {
        $brands = Brand::all();
        $brand = $request->get('brand', $brands->first()->id ?? 1);

        // Ambil data sample berdasarkan brand
        $samples = Sample::where('brand', $brand)->get()->groupBy('bulan');

        // Ambil bulan & tahun awal dari session
        $startMonth = session('startMonth', 1); // default Januari
        $startYear = session('startYear', now()->year);

        $data = [];
        $hasData = false;

        // Loop 12 bulan mulai dari bulan yang dipilih
        for ($i = 0; $i < 12; $i++) {
            $date = Carbon::create($startYear, $startMonth)->addMonths($i);
            $bulan = $date->month;

            $mingguData = [];

            if (isset($samples[$bulan])) {
                for ($minggu = 1; $minggu <= 4; $minggu++) {
                    $item = $samples[$bulan]->firstWhere('minggu', $minggu);
                    $mingguData[] = $item ? $item->data : null;
                }

                $data[] = [
                    // 'bulan' => $this->getNamaBulan($bulan),
                    'bulan' => $this->getNamaBulan($bulan) . ' ' . $date->year,
                    'minggu' => $mingguData,
                ];

                $hasData = true;
            }
        }

        return view('sample', compact('data', 'brand', 'hasData', 'brands'));
    }

    // public function generate(Request $request)
    // {
    //     // Jalankan query insert data sample
    //     DB::insert("
    //     INSERT INTO samples (brand, bulan, minggu, data)
    //     SELECT
    //         p.brand_id AS brand,
    //         m.month AS bulan,
    //         w.minggu AS minggu,
    //         COUNT(c.id) AS data
    //     FROM
    //         (SELECT 1 AS month UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4
    //          UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8
    //          UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12) m
    //     CROSS JOIN
    //         (SELECT 1 AS minggu, 1 AS start_day, 7 AS end_day
    //          UNION ALL SELECT 2, 8, 14
    //          UNION ALL SELECT 3, 15, 21
    //          UNION ALL SELECT 4, 22, 31) w
    //     JOIN
    //         products p ON p.status = 'aktif'
    //     LEFT JOIN
    //         cashiers c ON c.produk_id = p.id
    //                    AND MONTH(c.createdAt) = m.month
    //                    AND DAY(c.createdAt) BETWEEN w.start_day AND w.end_day
    //                    AND YEAR(c.createdAt) = 2024
    //     GROUP BY
    //         p.brand_id, m.month, w.minggu
    //     ORDER BY
    //         p.brand_id, m.month, w.minggu
    // ");

    //     return redirect()->route('sample.index')->with('success', 'Sample data berhasil diambil.');
    // }

    public function generate(Request $request)
    {
        $startMonth = (int) $request->input('bulan');
        $startYear = (int) $request->input('tahun');

        // Ambil brand_id dari produk yang aktif dan termasuk dalam kategori SMARTPHONE
        $brands = DB::table('products')->join('categories', 'products.category_id', '=', 'categories.id')->where('products.status', 'aktif')->where('categories.nama_kategori', 'SMARTPHONE')->distinct()->pluck('products.brand_id');

        $allData = [];

        foreach ($brands as $brand) {
            for ($i = 0; $i < 12; $i++) {
                $targetDate = \Carbon\Carbon::create($startYear, $startMonth)->addMonths($i);
                $bulan = $targetDate->month;
                $tahun = $targetDate->year;

                $results = DB::select(
                    "
            SELECT
                ? AS brand,
                ? AS bulan,
                w.minggu AS minggu,
                COUNT(c.id) AS data,
                NOW() AS createdAt,
                NOW() AS updatedAt
            FROM
                (SELECT 1 AS minggu, 1 AS start_day, 7 AS end_day
                 UNION ALL SELECT 2, 8, 14
                 UNION ALL SELECT 3, 15, 21
                 UNION ALL SELECT 4, 22, 31) w
            JOIN
                products p ON p.brand_id = ?
                AND p.status = 'aktif'
            LEFT JOIN
                cashiers c ON c.produk_id = p.id
                           AND MONTH(c.createdAt) = ?
                           AND DAY(c.createdAt) BETWEEN w.start_day AND w.end_day
                           AND YEAR(c.createdAt) = ?
            WHERE
                EXISTS (
                    SELECT 1 FROM categories cat WHERE cat.id = p.category_id AND cat.nama_kategori = 'SMARTPHONE'
                )
            GROUP BY
                w.minggu
            ORDER BY
                w.minggu
        ",
                    [$brand, $bulan, $brand, $bulan, $tahun],
                );

                foreach ($results as $row) {
                    $allData[] = [
                        'brand' => $row->brand,
                        'bulan' => $row->bulan,
                        'minggu' => $row->minggu,
                        'data' => $row->data,
                        'createdAt' => $row->createdAt,
                        'updatedAt' => $row->updatedAt,
                    ];
                }
            }
        }

        // Insert semua data sekaligus (hindari lompat ID)
        if (!empty($allData)) {
            DB::table('samples')->insert($allData);
        }

        session([
            'startMonth' => $startMonth,
            'startYear' => $startYear,
        ]);

        return redirect()->route('sample.index')->with('success', 'Sample data selama 12 bulan berhasil diambil.');
    }

    public function reset()
    {
        // Truncate semua tabel terkait
        DB::table('samples')->truncate();
        DB::table('training')->truncate();
        DB::table('testing')->truncate();
        DB::table('hasil')->truncate();
        DB::table('peringkat')->truncate();

        return redirect()->route('sample.index')->with('success', 'Data Sample, Training, dan Testing berhasil direset.');
    }

    private function getNamaBulan($angka)
    {
        $bulan = [
            1 => 'Januari',
            2 => 'Februari',
            3 => 'Maret',
            4 => 'April',
            5 => 'Mei',
            6 => 'Juni',
            7 => 'Juli',
            8 => 'Agustus',
            9 => 'September',
            10 => 'Oktober',
            11 => 'November',
            12 => 'Desember',
        ];

        // Mengembalikan nama bulan atau 'Tidak diketahui' jika bulan tidak ada
        return $bulan[$angka] ?? 'Tidak diketahui';
    }
}
