<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\SalesProgram;
use App\Models\Product; // TAMBAHAN: Untuk mengecek tipe produk
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;

class SalesProgramController extends Controller
{
    // 1. Tampilkan Semua Program Promo (Untuk Tabel di Next.js Admin)
    public function index(Request $request)
    {
        // PERBAIKAN: Menghapus relasi targetCustomerType karena sudah bermigrasi ke multiple array JSON
        $programs = SalesProgram::with(['category', 'product'])
            ->orderBy('created_at', 'desc')
            ->get();

        // Menyisipkan data tiers ke masing-masing program dengan relasi produk bonus
        $programIds = $programs->pluck('id');
        $allTiers = DB::table('sales_program_tiers')
            ->leftJoin('products', 'sales_program_tiers.bonus_product_id', '=', 'products.id')
            ->whereIn('sales_program_tiers.sales_program_id', $programIds)
            ->select('sales_program_tiers.*', 'products.name as bonus_product_name')
            ->get()
            ->groupBy('sales_program_id');

        $programs->transform(function ($program) use ($allTiers) {
            $program->tiers = $allTiers->get($program->id, []);
            return $program;
        });

        return response()->json([
            'status' => 'success',
            'data' => $programs
        ]);
    }

    // 2. Simpan Program Promo Baru
    public function store(Request $request)
    {
        $user = auth()->user();

        // PERBAIKAN ENTERPRISE: Kunci Otorisasi Master Data Pusat
        if ($user && !in_array($user->role, ['owner', 'manager'])) {
            return response()->json(['status' => 'error', 'message' => 'Akses ditolak: Hanya Manajemen Pusat (Owner/Manager) yang berhak membuat Program Promo.'], 403);
        }

        $validator = Validator::make($request->all(), [
            'nama_program' => 'required|string|max:255',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
            'target_type' => 'required|in:product,category,global',
            'target_customer_types' => 'nullable|array', // TAMBAHAN: Validasi Checklist Tipe Outlet
            'tiers' => 'required|array',
            'tiers.*.min_qty' => 'required|numeric',
            'tiers.*.reward_type' => 'required|in:discount_percent,discount_nominal,bonus_item',
            // Tambahkan validasi untuk is_multiple
            'tiers.*.is_multiple' => 'nullable|boolean'
        ]);

        if ($validator->fails()) {
            return response()->json(['status' => 'error', 'errors' => $validator->errors()], 422);
        }

        // PERBAIKAN: Validasi ketat agar Bahan Baku & Penolong tidak bisa dijadikan Target Promo
        if ($request->target_type === 'product' && $request->filled('product_id')) {
            $targetProduct = Product::find($request->product_id);
            if ($targetProduct && in_array($targetProduct->product_type, ['raw_material', 'consumable'])) {
                return response()->json(['status' => 'error', 'message' => 'Validasi Gagal: Produk Bahan Baku atau Bahan Penolong tidak dapat diikutkan dalam program promo.'], 422);
            }
        }

        // PERBAIKAN: Validasi ketat agar Bahan Baku & Penolong tidak bisa dijadikan Produk Bonus
        if ($request->has('tiers')) {
            foreach ($request->tiers as $tier) {
                if (!empty($tier['bonus_product_id'])) {
                    $bonusProduct = Product::find($tier['bonus_product_id']);
                    if ($bonusProduct && in_array($bonusProduct->product_type, ['raw_material', 'consumable'])) {
                        return response()->json(['status' => 'error', 'message' => 'Validasi Gagal: Produk Bahan Baku atau Bahan Penolong tidak dapat dijadikan hadiah/bonus promo.'], 422);
                    }
                }
            }
        }

        try {
            DB::beginTransaction();

            $program = SalesProgram::create([
                'nama_program' => $request->nama_program,
                'description' => $request->description,
                'start_date' => $request->start_date,
                'end_date' => $request->end_date,
                'target_type' => $request->target_type,
                'product_id' => $request->product_id,
                'category_id' => $request->category_id,
                'target_customer_types' => $request->target_customer_types, // TAMBAHAN: Simpan Array Tipe Outlet
                'is_active' => true,
            ]);

            foreach ($request->tiers as $tier) {
                DB::table('sales_program_tiers')->insert([
                    'sales_program_id' => $program->id,
                    'min_qty' => $tier['min_qty'],
                    'reward_type' => $tier['reward_type'],
                    'reward_value' => $tier['reward_value'] ?? 0,
                    'bonus_qty' => $tier['bonus_qty'] ?? 0,
                    'bonus_product_id' => $tier['bonus_product_id'] ?? null,
                    // Simpan status kelipatan di sini
                    'is_multiple' => $tier['is_multiple'] ?? false,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }

            DB::commit();
            return response()->json(['status' => 'success', 'message' => 'Program Promo berhasil dibuat']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['status' => 'error', 'message' => $e->getMessage()], 500);
        }
    }

    // 3. Tampilkan Detail 1 Promo (Untuk Form Edit)
    public function show($id)
    {
        // PERBAIKAN: Menghapus relasi targetCustomerType dari Eager Loading
        $program = SalesProgram::with(['category', 'product'])->find($id);

        if (!$program) {
            return response()->json(['status' => 'error', 'message' => 'Promo tidak ditemukan'], 404);
        }

        // PERBAIKAN: Menambahkan relasi Join ke tabel Products agar bonus_product_name muncul di form edit
        $tiers = DB::table('sales_program_tiers')
            ->leftJoin('products', 'sales_program_tiers.bonus_product_id', '=', 'products.id')
            ->where('sales_program_tiers.sales_program_id', $id)
            ->select('sales_program_tiers.*', 'products.name as bonus_product_name')
            ->get();
            
        $program->tiers = $tiers;

        return response()->json([
            'status' => 'success',
            'data' => $program
        ]);
    }

    // 4. Update Program Promo
    public function update(Request $request, $id)
    {
        $user = auth()->user();

        // PERBAIKAN ENTERPRISE: Kunci Otorisasi Master Data Pusat
        if ($user && !in_array($user->role, ['owner', 'manager'])) {
            return response()->json(['status' => 'error', 'message' => 'Akses ditolak: Hanya Manajemen Pusat (Owner/Manager) yang berhak mengubah Program Promo.'], 403);
        }

        $program = SalesProgram::find($id);

        if (!$program) {
            return response()->json(['status' => 'error', 'message' => 'Promo tidak ditemukan'], 404);
        }

        $validator = Validator::make($request->all(), [
            'nama_program' => 'required|string|max:255',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
            'target_type' => 'required|in:product,parent,category,global',
            'target_customer_types' => 'nullable|array', // TAMBAHAN: Validasi Checklist Tipe Outlet
            'tiers' => 'required|array|min:1',
            'tiers.*.is_multiple' => 'nullable|boolean' // Tambahan validasi
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'message' => 'Data tidak valid',
                'errors' => $validator->errors()
            ], 422);
        }

        // PERBAIKAN: Validasi ketat agar Bahan Baku & Penolong tidak bisa dijadikan Target Promo
        if (in_array($request->target_type, ['product', 'parent']) && $request->filled('target_id')) {
            $targetProduct = Product::find($request->target_id);
            if ($targetProduct && in_array($targetProduct->product_type, ['raw_material', 'consumable'])) {
                return response()->json(['status' => 'error', 'message' => 'Validasi Gagal: Produk Bahan Baku atau Bahan Penolong tidak dapat diikutkan dalam program promo.'], 422);
            }
        }

        // PERBAIKAN: Validasi ketat agar Bahan Baku & Penolong tidak bisa dijadikan Produk Bonus
        if ($request->has('tiers')) {
            foreach ($request->tiers as $tier) {
                if (!empty($tier['bonus_product_id'])) {
                    $bonusProduct = Product::find($tier['bonus_product_id']);
                    if ($bonusProduct && in_array($bonusProduct->product_type, ['raw_material', 'consumable'])) {
                        return response()->json(['status' => 'error', 'message' => 'Validasi Gagal: Produk Bahan Baku atau Bahan Penolong tidak dapat dijadikan hadiah/bonus promo.'], 422);
                    }
                }
            }
        }

        DB::beginTransaction();
        try {
            // A. Pemetaan Scope dan ID Target
            $scope = 'global';
            $categoryId = null;
            $productId = null;

            if ($request->target_type === 'category') {
                $scope = 'category';
                $categoryId = $request->target_id;
            } else if (in_array($request->target_type, ['product', 'parent'])) {
                $scope = 'product';
                $productId = $request->target_id;
            }

            // B. Ekstraksi Tier 1 (Index 0) untuk Legacy Fallback
            $firstTier = $request->tiers[0] ?? null;
            $legacyMinQty = $firstTier ? $firstTier['min_qty'] : 0;
            $legacyDiscountPercent = 0;
            $legacyDiscountNominal = 0;
            $legacyFreeProductId = null;
            $legacyFreeQty = 0;

            if ($firstTier) {
                if ($firstTier['reward_type'] === 'discount_percent') {
                    $parts = explode('+', $firstTier['reward_value']);
                    $legacyDiscountPercent = is_numeric($parts[0]) ? $parts[0] : 0;
                } elseif ($firstTier['reward_type'] === 'discount_nominal') {
                    $legacyDiscountNominal = is_numeric($firstTier['reward_value']) ? $firstTier['reward_value'] : 0;
                } elseif ($firstTier['reward_type'] === 'bonus_item') {
                    $legacyFreeProductId = !empty($firstTier['bonus_product_id']) ? $firstTier['bonus_product_id'] : null;
                    $legacyFreeQty = $firstTier['bonus_qty'] ?? 0;
                }
            }

            // C. Update tabel utama
            $program->update([
                'nama_program' => $request->nama_program,
                'start_date' => $request->start_date,
                'end_date' => $request->end_date,
                'target_customer_levels' => $request->target_customer_levels ?? $program->target_customer_levels,
                'scope' => $scope,
                'category_id' => $categoryId,
                'product_id' => $productId,
                'target_customer_types' => $request->has('target_customer_types') ? $request->target_customer_types : $program->target_customer_types, // TAMBAHAN: Update Array Checklist
                'min_qty' => $legacyMinQty,
                'discount_percent' => $legacyDiscountPercent,
                'discount_nominal' => $legacyDiscountNominal,
                'free_product_id' => $legacyFreeProductId,
                'free_qty' => $legacyFreeQty,
                'is_active' => $request->has('is_active') ? $request->is_active : $program->is_active,
            ]);

            // D. Sinkronisasi Tiers (Hapus yang lama, insert yang baru)
            DB::table('sales_program_tiers')->where('sales_program_id', $program->id)->delete();

            foreach ($request->tiers as $tier) {
                DB::table('sales_program_tiers')->insert([
                    'sales_program_id' => $program->id,
                    'min_qty' => $tier['min_qty'] ?? 0,
                    'max_qty' => $tier['max_qty'] ?? 0,
                    'reward_type' => $tier['reward_type'],
                    'reward_value' => $tier['reward_value'] ?? '',
                    'bonus_product_id' => !empty($tier['bonus_product_id']) ? $tier['bonus_product_id'] : null,
                    'bonus_qty' => $tier['bonus_qty'] ?? 0,
                    'is_multiple' => isset($tier['is_multiple']) ? $tier['is_multiple'] : false, // Simpan status kelipatan
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }

            DB::commit();
            
            $program->tiers = $request->tiers;

            return response()->json([
                'status' => 'success',
                'message' => 'Program Promo berhasil diupdate!',
                'data' => $program
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['status' => 'error', 'message' => $e->getMessage()], 500);
        }
    }

    // 5. Hapus Program Promo
    public function destroy($id)
    {
        $user = auth()->user();

        // PERBAIKAN ENTERPRISE: Kunci Otorisasi Master Data Pusat
        if ($user && !in_array($user->role, ['owner', 'manager'])) {
            return response()->json(['status' => 'error', 'message' => 'Akses ditolak: Hanya Manajemen Pusat (Owner/Manager) yang berhak menghapus Program Promo.'], 403);
        }

        $program = SalesProgram::find($id);

        if (!$program) {
            return response()->json(['status' => 'error', 'message' => 'Promo tidak ditemukan'], 404);
        }

        // DB otomatis menghapus child tiers jika foreign key diset cascade
        $program->delete();

        return response()->json([
            'status' => 'success',
            'message' => 'Program Promo berhasil dihapus.'
        ]);
    }
    
    // 6. Endpoint Khusus: Ambil Promo yang Sedang Aktif Hari Ini (Untuk dipakai Checkout nanti)
    public function getActivePrograms()
    {
        $today = date('Y-m-d');
        // PERBAIKAN: Menghapus relasi targetCustomerType dari Eager Loading di sini juga
        $activePrograms = SalesProgram::with(['category', 'product'])
            ->where('is_active', true)
            ->where('start_date', '<=', $today)
            ->where('end_date', '>=', $today)
            ->get();
            
        // Sisipkan Tiers ke dalam response dengan relasi produk bonus
        $programIds = $activePrograms->pluck('id');
        $allTiers = DB::table('sales_program_tiers')
            ->leftJoin('products', 'sales_program_tiers.bonus_product_id', '=', 'products.id')
            ->whereIn('sales_program_tiers.sales_program_id', $programIds)
            ->select('sales_program_tiers.*', 'products.name as bonus_product_name')
            ->get()
            ->groupBy('sales_program_id');

        $activePrograms->transform(function ($program) use ($allTiers) {
            $program->tiers = $allTiers->get($program->id, []);
            return $program;
        });

        return response()->json([
            'status' => 'success',
            'data' => $activePrograms
        ]);
    }
}