<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\MasterJourneyPlan;
use Illuminate\Database\QueryException; // PENAMBAHAN: Standar ERP untuk menangkap error constraint database

class AdminJourneyPlanController extends Controller
{
    public function index(Request $request)
    {
        try {
            $user = $request->user();

            $query = DB::table('master_journey_plans as mjp')
                ->join('salesmen as s', 'mjp.salesman_id', '=', 's.id')
                ->join('users as u', 's.user_id', '=', 'u.id')
                ->join('customers as c', 'mjp.customer_id', '=', 'c.id')
                // Join untuk mengambil data wilayah
                ->leftJoin('districts as d', 'c.district_id', '=', 'd.id')
                ->leftJoin('cities as ct', 'd.city_id', '=', 'ct.id')
                ->select(
                    'mjp.*', 
                    'u.name as salesman_name', 
                    'c.name as customer_name',
                    'c.address as customer_address', // Tambahkan Alamat
                    'ct.name as city_name'           // Tambahkan Kota
                );

            // PENAMBAHAN: Filter Cabang
            // Memastikan admin hanya melihat jadwal kunjungan untuk pelanggan di cabangnya sendiri
            if ($user && $user->role !== 'owner') {
                $query->where('c.branch_id', $user->branch_id);
            }

            $plans = $query->orderBy('mjp.day_of_week')
                ->orderBy('u.name')
                ->get();

            return response()->json(['success' => true, 'data' => $plans]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false, 
                'message' => 'Error Load Journey Plan: ' . $e->getMessage()
            ], 500);
        }
    }

    public function store(Request $request)
    {
        $request->validate([
            'salesman_id' => 'required|exists:salesmen,id',
            'customer_id' => 'required|exists:customers,id',
            'day_of_week' => 'required|numeric|between:1,6',
            'frequency_type' => 'required|in:weekly,biweekly_odd,biweekly_even,monthly',
            'week_number' => 'required_if:frequency_type,monthly'
        ]);

        // PENAMBAHAN: Proteksi Ganda Hak Akses Cabang saat pembuatan jadwal
        $user = $request->user();
        if ($user && $user->role !== 'owner') {
            // 1. Validasi Cabang Pelanggan
            $customer = DB::table('customers')->where('id', $request->customer_id)->first();
            if ($customer && $customer->branch_id !== $user->branch_id) {
                return response()->json(['success' => false, 'message' => 'Akses ditolak: Anda tidak dapat membuat jadwal untuk pelanggan dari cabang lain.'], 403);
            }

            // 2. Validasi Cabang Salesman (Mencegah bajak pegawai antar cabang)
            $salesman = DB::table('salesmen')
                ->join('users', 'salesmen.user_id', '=', 'users.id')
                ->where('salesmen.id', $request->salesman_id)
                ->select('users.branch_id')
                ->first();
                
            if ($salesman && $salesman->branch_id !== $user->branch_id) {
                return response()->json(['success' => false, 'message' => 'Akses ditolak: Salesman yang dipilih berasal dari cabang lain.'], 403);
            }
        }

        MasterJourneyPlan::create($request->all());

        return response()->json(['success' => true, 'message' => 'Jadwal berhasil ditambahkan.']);
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'salesman_id' => 'required|exists:salesmen,id',
            'customer_id' => 'required|exists:customers,id',
            'day_of_week' => 'required|numeric|between:1,6',
            'frequency_type' => 'required|in:weekly,biweekly_odd,biweekly_even,monthly',
            'week_number' => 'required_if:frequency_type,monthly'
        ]);

        $plan = MasterJourneyPlan::findOrFail($id);
        $user = $request->user();

        // PENAMBAHAN: Proteksi Ganda Hak Akses Cabang saat update
        if ($user && $user->role !== 'owner') {
            // 1A. Cek pelanggan lama
            $oldCustomer = DB::table('customers')->where('id', $plan->customer_id)->first();
            if ($oldCustomer && $oldCustomer->branch_id !== $user->branch_id) {
                return response()->json(['success' => false, 'message' => 'Akses ditolak: Anda tidak memiliki hak untuk mengubah jadwal cabang lain.'], 403);
            }

            // 1B. Cek pelanggan baru (jika customer_id diubah)
            $newCustomer = DB::table('customers')->where('id', $request->customer_id)->first();
            if ($newCustomer && $newCustomer->branch_id !== $user->branch_id) {
                return response()->json(['success' => false, 'message' => 'Akses ditolak: Pelanggan tujuan berada di cabang lain.'], 403);
            }

            // 2. Cek salesman baru (jika salesman_id diubah)
            $newSalesman = DB::table('salesmen')
                ->join('users', 'salesmen.user_id', '=', 'users.id')
                ->where('salesmen.id', $request->salesman_id)
                ->select('users.branch_id')
                ->first();

            if ($newSalesman && $newSalesman->branch_id !== $user->branch_id) {
                return response()->json(['success' => false, 'message' => 'Akses ditolak: Salesman tujuan berasal dari cabang lain.'], 403);
            }
        }

        $plan->update($request->all());

        return response()->json(['success' => true, 'message' => 'Jadwal berhasil diupdate.']);
    }

    public function destroy(Request $request, $id)
    {
        try {
            $plan = MasterJourneyPlan::findOrFail($id);
            $user = $request->user();

            // PENAMBAHAN: Proteksi Hak Akses Cabang saat delete
            if ($user && $user->role !== 'owner') {
                $customer = DB::table('customers')->where('id', $plan->customer_id)->first();
                if ($customer && $customer->branch_id !== $user->branch_id) {
                    return response()->json(['success' => false, 'message' => 'Akses ditolak: Anda tidak memiliki hak untuk menghapus jadwal cabang lain.'], 403);
                }
            }

            $plan->delete();
            return response()->json(['success' => true, 'message' => 'Jadwal berhasil dihapus.']);
            
        } catch (QueryException $e) {
            // PROTEKSI ENTERPRISE: Menangkap error constraint violation
            // Mencegah penghapusan jika Master Journey Plan ini menjadi referensi log kunjungan harian yang sudah terjadi
            if ($e->getCode() == "23000") {
                return response()->json([
                    'success' => false, 
                    'message' => 'Gagal menghapus: Jadwal ini sudah memiliki riwayat kunjungan aktual di lapangan. Silakan nonaktifkan atau ubah hari kunjungannya alih-alih menghapusnya.'
                ], 400);
            }
            return response()->json(['success' => false, 'message' => 'Database Error.'], 500);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}