<?php

namespace App\Http\Controllers\Leasing;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\StoreLeasingRecordRequest;
use App\Http\Requests\Auth\UpdateLeasingRecordRequest;
use App\Models\LeasingRecord;
use App\Models\Branch;
use App\Services\AuditLogService;
use Illuminate\Http\Request;

class RecordController extends Controller
{
    protected $auditLog;

    public function __construct(AuditLogService $auditLog)
    {
        $this->auditLog = $auditLog;
    }

    public function index(Request $request)
    {
        $this->authorize('viewAny', LeasingRecord::class);
        
        $profile = auth()->user()->leasingProfile;

        $query = $profile->records()->with('branch');

        if ($request->filled('search')) {
            $query->where(function($q) use ($request) {
                $search = $request->search;
                $q->where('nopol', 'like', "%{$search}%")
                  ->orWhere('rangka', 'like', "%{$search}%")
                  ->orWhere('mesin', 'like', "%{$search}%")
                  ->orWhere('model', 'like', "%{$search}%");
            });
        }

        if ($request->filled('branch_id')) {
            $query->where('branch_id', $request->branch_id);
        }

        $records = $query->latest()->paginate(20);
        $branches = $profile->branches;

        return view('leasing.records.index', compact('records', 'branches'));
    }

    public function create()
    {
        $this->authorize('create', LeasingRecord::class);
        $profile = auth()->user()->leasingProfile;

        $branches = $profile->branches;
        
        if ($branches->isEmpty()) {
            return redirect()->route('leasing.branches.create')->with('warning', 'Harap buat minimal satu cabang sebelum menambah data kendaraan.');
        }

        return view('leasing.records.create', compact('branches'));
    }

    public function store(StoreLeasingRecordRequest $request)
    {
        $this->authorize('create', LeasingRecord::class);
        
        $data = $request->validated();
        $profile = auth()->user()->leasingProfile;

        // Strict branch ownership verification
        $branch = $profile->branches()->where('id', $data['branch_id'])->firstOrFail();

        $data['leasing_profile_id'] = $profile->id;
        $record = LeasingRecord::create($data);
        
        $this->auditLog->log('RECORD_CREATED', $record);

        return redirect()->route('leasing.records.index')->with('success', 'Unit kendaraan '. $record->nopol .' berhasil didaftarkan secara manual.');
    }

    public function show(LeasingRecord $record)
    {
        $this->authorize('view', $record);
        return view('leasing.records.show', compact('record'));
    }

    public function edit(LeasingRecord $record)
    {
        $this->authorize('update', $record);
        $profile = auth()->user()->leasingProfile;

        $branches = $profile->branches;
        return view('leasing.records.edit', compact('record', 'branches'));
    }

    public function update(UpdateLeasingRecordRequest $request, LeasingRecord $record)
    {
        $this->authorize('update', $record);
        
        $data = $request->validated();
        $profile = auth()->user()->leasingProfile;

        // Strict branch ownership verification
        if (isset($data['branch_id'])) {
            $profile->branches()->where('id', $data['branch_id'])->firstOrFail();
        }

        $record->update($data);
        $this->auditLog->log('RECORD_UPDATED', $record);

        return redirect()->route('leasing.records.index')->with('success', 'Data unit '. $record->nopol .' berhasil diperbarui.');
    }

    public function destroy(LeasingRecord $record)
    {
        $this->authorize('delete', $record);
        
        $nopol = $record->nopol;
        $this->auditLog->log('RECORD_DELETED', $record, $record->toArray());
        
        $record->delete();
        
        return back()->with('success', 'Unit '. $nopol .' telah dihapus dari sistem.');
    }
}
