<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SalaryAdvance;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SalaryAdvanceController extends Controller
{
    public function index()
    {
        $advances = SalaryAdvance::with(['user', 'approver'])
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        return view('admin.salary_advances.index', compact('advances'));
    }

    public function create()
    {
        $users = User::whereHas('role', function($q) {
            $q->where('name', 'Sales Representative');
        })->get();

        return view('admin.salary_advances.create', compact('users'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'user_id' => 'required|exists:users,id',
            'amount' => 'required|numeric|min:0',
            'advance_date' => 'required|date',
            'reason' => 'nullable|string',
        ]);

        SalaryAdvance::create([
            'user_id' => $request->user_id,
            'amount' => $request->amount,
            'advance_date' => $request->advance_date,
            'remaining_amount' => $request->amount,
            'reason' => $request->reason,
            'approved_by' => Auth::id(),
            'status' => 'pending',
        ]);

        return redirect()->route('admin.salary-advances.index')
            ->with('success', 'Salary advance created successfully');
    }

    public function show($id)
    {
        $advance = SalaryAdvance::with(['user', 'approver'])->findOrFail($id);
        return view('admin.salary_advances.show', compact('advance'));
    }

    public function edit($id)
    {
        $advance = SalaryAdvance::findOrFail($id);
        $users = User::whereHas('role', function($q) {
            $q->where('name', 'Sales Representative');
        })->get();

        return view('admin.salary_advances.edit', compact('advance', 'users'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'amount' => 'required|numeric|min:0',
            'advance_date' => 'required|date',
            'reason' => 'nullable|string',
        ]);

        $advance = SalaryAdvance::findOrFail($id);
        
        // Recalculate remaining amount if total amount changed
        $amountDifference = $request->amount - $advance->amount;
        $newRemainingAmount = $advance->remaining_amount + $amountDifference;

        $advance->update([
            'amount' => $request->amount,
            'advance_date' => $request->advance_date,
            'remaining_amount' => max(0, $newRemainingAmount),
            'reason' => $request->reason,
        ]);

        return redirect()->route('admin.salary-advances.index')
            ->with('success', 'Salary advance updated successfully');
    }

    public function destroy($id)
    {
        $advance = SalaryAdvance::findOrFail($id);
        
        if ($advance->status !== 'pending') {
            return back()->with('error', 'Cannot delete a salary advance that has been deducted');
        }

        $advance->delete();

        return redirect()->route('admin.salary-advances.index')
            ->with('success', 'Salary advance deleted successfully');
    }
}
