<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\HoldCart; 
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class HoldCartController extends Controller
{
    // A. SIMPAN KERANJANG (HOLD)
    public function saveCart(Request $request)
    {
        $request->validate([
            'hold_name' => 'required|string|max:255',
            'customer_id' => 'nullable|integer',
            'customer_name' => 'nullable|string',
            'items_json' => 'required|json', // Berisi JSON string dari item
            'branch_id' => 'nullable|integer|exists:branches,id' // TAMBAHAN: Opsional untuk Owner
        ]);

        $user = $request->user();

        // PENAMBAHAN ENTERPRISE: Amankan rute cabang untuk Role Owner
        $branchId = ($user->role === 'owner' && $request->filled('branch_id')) 
                    ? $request->branch_id 
                    : ($user->branch_id ?? 1);

        try {
            HoldCart::create([
                'branch_id' => $branchId,
                'user_id' => $user->id,
                'hold_name' => $request->hold_name,
                'customer_id' => $request->customer_id,
                'customer_name' => $request->customer_name,
                'items_json' => $request->items_json,
                'created_at' => Carbon::now(),
            ]);

            return response()->json(['success' => true, 'message' => 'Keranjang berhasil disimpan.'], 201);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Gagal menyimpan keranjang: ' . $e->getMessage()], 500);
        }
    }

    // B. LIST KERANJANG YANG DI HOLD
    public function fetchHeldCarts(Request $request)
    {
        $user = $request->user();
        
        $query = HoldCart::orderBy('created_at', 'desc');

        // PENAMBAHAN: Filter Cabang Dinamis
        if ($user && $user->role !== 'owner') {
            $query->where('branch_id', $user->branch_id);
        } elseif ($request->filled('branch_id')) {
            $query->where('branch_id', $request->branch_id);
        }

        $carts = $query->get(['id', 'hold_name', 'customer_name', 'created_at']);

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

    // C. LOAD DETAIL KERANJANG BERDASARKAN ID
    public function loadCart($id, Request $request)
    {
        $user = $request->user();

        $query = HoldCart::where('id', $id);

        // PENAMBAHAN: Isolasi Cabang
        if ($user && $user->role !== 'owner') {
            $query->where('branch_id', $user->branch_id);
        }

        $cart = $query->first();

        if (!$cart) {
            return response()->json(['success' => false, 'message' => 'Data hold cart tidak ditemukan atau bukan milik cabang Anda.'], 404);
        }

        // Kembalikan semua data, termasuk items_json (string)
        return response()->json(['success' => true, 'data' => $cart]);
    }

    // D. DELETE KERANJANG
    public function deleteCart($id, Request $request)
    {
        try {
            $user = $request->user();
            
            $query = HoldCart::where('id', $id);

            // PENAMBAHAN: Isolasi Cabang
            if ($user && $user->role !== 'owner') {
                $query->where('branch_id', $user->branch_id);
            }
            
            $deleted = $query->delete();

            if (!$deleted) {
                return response()->json(['success' => false, 'message' => 'Gagal menghapus: Data tidak ditemukan atau Anda tidak memiliki akses ke cabang ini.'], 404);
            }

            return response()->json(['success' => true, 'message' => 'Keranjang berhasil dihapus.']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Terjadi kesalahan sistem: ' . $e->getMessage()], 500);
        }
    }
}