<?php

namespace App\Http\Controllers\Api;

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

class DriverAssignmentController extends Controller
{
    /**
     * Menampilkan semua daftar penugasan supir
     */
    public function index(Request $request)
    {
        try {
            $user = $request->user();
            $query = DB::table('driver_assignments as da')
                ->join('users as u', 'da.driver_id', '=', 'u.id')
                ->join('armadas as a', 'da.armada_id', '=', 'a.id')
                ->join('branches as b', 'da.branch_id', '=', 'b.id')
                ->select(
                    'da.*', 
                    'u.name as driver_name', 
                    'a.name as vehicle_name', 
                    'a.license_plate', 
                    'b.name as branch_name'
                );

            // PENAMBAHAN: Isolasi Data Penugasan Cabang
            if ($user && $user->role !== 'owner') {
                $query->where('da.branch_id', $user->branch_id);
            } elseif ($request->filled('branch_id')) {
                $query->where('da.branch_id', $request->branch_id);
            }

            return response()->json(['success' => true, 'data' => $query->get()]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Gagal mengambil data: ' . $e->getMessage()], 500);
        }
    }

    /**
     * Mengambil data supir, armada, dan cabang untuk dropdown di Modal
     */
    public function getFormData(Request $request)
    {
        try {
            $user = $request->user();
            
            $driverQuery = DB::table('users')->where('role', 'driver')->select('id', 'name');
            $armadaQuery = DB::table('armadas')->select('id', 'name', 'license_plate');
            $branchQuery = DB::table('branches')->select('id', 'name');

            // PENAMBAHAN: Isolasi Dropdown untuk Admin Cabang
            if ($user && $user->role !== 'owner') {
                $driverQuery->where('branch_id', $user->branch_id);
                $armadaQuery->where('branch_id', $user->branch_id);
                $branchQuery->where('id', $user->branch_id);
            }
            
            return response()->json([
                'drivers' => $driverQuery->get(),
                'armadas' => $armadaQuery->get(),
                'branches' => $branchQuery->get()
            ]);
        } catch (\Exception $e) {
            return response()->json(['message' => $e->getMessage()], 500);
        }
    }

    /**
     * Menyimpan penugasan supir baru
     */
    public function store(Request $request)
    {
        $request->validate([
            'driver_id' => 'required',
            'armada_id' => 'required',
            'branch_id' => 'required'
        ]);

        $user = $request->user();

        // PENAMBAHAN: Validasi Silang Cabang (Cegah Penugasan Lintas Cabang yang Ilegal)
        if ($user && $user->role !== 'owner' && (int)$request->branch_id !== (int)$user->branch_id) {
            return response()->json(['success' => false, 'message' => 'Akses ditolak: Anda tidak dapat menugaskan supir ke cabang lain.'], 403);
        }

        try {
            DB::table('driver_assignments')->insert([
                'driver_id' => $request->driver_id,
                'armada_id' => $request->armada_id,
                'branch_id' => $request->branch_id,
                'is_active' => $request->is_active ? 1 : 0,
                'notes' => $request->notes,
                'created_at' => now(),
                'updated_at' => now()
            ]);
            return response()->json(['success' => true, 'message' => 'Penugasan berhasil disimpan']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * Memperbarui data penugasan (Edit)
     */
    public function update(Request $request, $id)
    {
        $user = $request->user();
        $assignment = DB::table('driver_assignments')->where('id', $id)->first();
        
        if (!$assignment) return response()->json(['success' => false, 'message' => 'Data tidak ditemukan'], 404);

        // PENAMBAHAN: Validasi Hak Akses Update
        if ($user && $user->role !== 'owner' && (int)$assignment->branch_id !== (int)$user->branch_id) {
            return response()->json(['success' => false, 'message' => 'Akses ditolak: Data penugasan ini bukan wewenang cabang Anda.'], 403);
        }

        try {
            DB::table('driver_assignments')->where('id', $id)->update([
                'driver_id' => $request->driver_id,
                'armada_id' => $request->armada_id,
                'branch_id' => $request->branch_id,
                'is_active' => $request->is_active ? 1 : 0,
                'notes' => $request->notes,
                'updated_at' => now()
            ]);
            return response()->json(['success' => true, 'message' => 'Penugasan berhasil diperbarui']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}