<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Salesman;
use App\Models\User; 
use Illuminate\Database\QueryException; 

class AdminSalesmanController extends Controller
{
    public function index(Request $request)
    {
        try {
            $authUser = $request->user();
            // PERBAIKAN: Load relasi berlapis 'user.branch' agar nama cabang ikut terbawa ke frontend
            $query = Salesman::with(['user.branch'])->orderBy('code', 'asc');
            
            // Isolasi Data Cabang
            if ($authUser && $authUser->role !== 'owner') {
                $query->whereHas('user', function($q) use ($authUser) {
                    $q->where('branch_id', $authUser->branch_id);
                });
            }

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

    public function store(Request $request)
    {
        $request->validate([
            'user_id' => 'required|exists:users,id|unique:salesmen,user_id',
            'code' => 'required|string|max:50|unique:salesmen,code',
            'area_cakupan' => 'nullable|string|max:255',
            'supervisor_id' => 'nullable|exists:users,id',
            'salesman_type' => 'required|in:TO,CANVAS', 
        ], [
            'user_id.unique' => 'User ini sudah terdaftar sebagai Salesman.',
            'code.unique' => 'Kode Salesman sudah digunakan.'
        ]);

        $authUser = $request->user();
        
        // Proteksi Pembajakan Karyawan Antar Cabang
        if ($authUser && $authUser->role !== 'owner') {
            $targetUser = User::find($request->user_id);
            if ($targetUser && $targetUser->branch_id !== $authUser->branch_id) {
                return response()->json(['success' => false, 'message' => 'Akses ditolak: User yang dipilih berada di cabang lain.'], 403);
            }

            if ($request->filled('supervisor_id')) {
                $targetSpv = User::find($request->supervisor_id);
                if ($targetSpv && $targetSpv->branch_id !== $authUser->branch_id) {
                    return response()->json(['success' => false, 'message' => 'Akses ditolak: Supervisor yang dipilih berada di cabang lain.'], 403);
                }
            }
        }

        try {
            $salesman = Salesman::create([
                'user_id' => $request->user_id,
                'code' => strtoupper($request->code),
                'area_cakupan' => strtoupper($request->area_cakupan),
                'supervisor_id' => $request->supervisor_id,
                'salesman_type' => $request->salesman_type,
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Profil Salesman berhasil dibuat',
                'data' => $salesman
            ], 201);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function update(Request $request, $id)
    {
        $salesman = Salesman::with('user')->findOrFail($id);
        $authUser = $request->user();

        // Proteksi Hak Akses Cabang
        if ($authUser && $authUser->role !== 'owner') {
            if ($salesman->user && $salesman->user->branch_id !== $authUser->branch_id) {
                return response()->json(['success' => false, 'message' => 'Akses ditolak: Anda tidak memiliki hak untuk mengubah data salesman cabang lain.'], 403);
            }
            
            $targetUser = User::find($request->user_id);
            if ($targetUser && $targetUser->branch_id !== $authUser->branch_id) {
                return response()->json(['success' => false, 'message' => 'Akses ditolak: User tujuan berada di cabang lain.'], 403);
            }

            if ($request->filled('supervisor_id')) {
                $targetSpv = User::find($request->supervisor_id);
                if ($targetSpv && $targetSpv->branch_id !== $authUser->branch_id) {
                    return response()->json(['success' => false, 'message' => 'Akses ditolak: Supervisor tujuan berada di cabang lain.'], 403);
                }
            }
        }

        $request->validate([
            'user_id' => 'required|exists:users,id|unique:salesmen,user_id,' . $id,
            'code' => 'required|string|max:50|unique:salesmen,code,' . $id,
            'area_cakupan' => 'nullable|string|max:255',
            'supervisor_id' => 'nullable|exists:users,id',
            'salesman_type' => 'required|in:TO,CANVAS', 
        ]);

        try {
            $salesman->update([
                'user_id' => $request->user_id,
                'code' => strtoupper($request->code),
                'area_cakupan' => strtoupper($request->area_cakupan),
                'supervisor_id' => $request->supervisor_id,
                'salesman_type' => $request->salesman_type,
            ]);

            return response()->json(['success' => true, 'message' => 'Profil Salesman berhasil diperbarui', 'data' => $salesman], 200);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function destroy(Request $request, $id)
    {
        try {
            $salesman = Salesman::with('user')->findOrFail($id);
            $authUser = $request->user();

            // Proteksi Hak Akses Cabang
            if ($authUser && $authUser->role !== 'owner') {
                if ($salesman->user && $salesman->user->branch_id !== $authUser->branch_id) {
                    return response()->json(['success' => false, 'message' => 'Akses ditolak: Anda tidak berhak menghapus profil salesman cabang lain.'], 403);
                }
            }

            $salesman->delete();
            return response()->json(['success' => true, 'message' => 'Profil Salesman berhasil dihapus'], 200);
            
        } catch (QueryException $e) {
            // PROTEKSI ENTERPRISE: Menangkap error constraint violation
            if ($e->getCode() == "23000") {
                return response()->json([
                    'success' => false, 
                    'message' => 'Gagal menghapus: Salesman ini sudah memiliki riwayat kunjungan atau transaksi di sistem. Harap nonaktifkan akun user-nya saja.'
                ], 400);
            }
            return response()->json(['success' => false, 'message' => 'Database Error.'], 500);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}