<?php

namespace App\Http\Controllers\Admin;

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

class SalaryController extends Controller
{
    public function index()
    {
        $shopId = $this->shopId();

        $staff = User::where('shop_id', $shopId)
            ->where('type_id', 3)
            ->with('salarySetting')
            ->withSum('salaryPayments', 'amount')
            ->get();

        return view('admin.salary.index', compact('staff'));
    }

    public function updateSettings(Request $request, User $staff)
    {
        abort_unless($staff->shop_id === $this->shopId(), 403);

        $data = $request->validate([
            'salary_type' => 'required|in:fixed,commission',
            'base_salary' => 'nullable|numeric|min:0',
            'commission_rate' => 'nullable|numeric|min:0|max:100',
        ]);

        StaffSalarySetting::updateOrCreate(
            ['staff_id' => $staff->id],
            $data
        );

        return back()->with('status', "{$staff->name}'s salary settings updated.");
    }

    public function show(User $staff)
    {
        abort_unless($staff->shop_id === $this->shopId(), 403);

        $staff->load('salarySetting');
        $payments = $staff->salaryPayments()->latest('paid_on')->get();
        $totalPaid = $payments->sum('amount');

        return view('admin.salary.show', compact('staff', 'payments', 'totalPaid'));
    }

    public function storePayment(Request $request, User $staff)
    {
        abort_unless($staff->shop_id === $this->shopId(), 403);

        $data = $request->validate([
            'amount' => 'required|numeric|min:0.01',
            'paid_on' => 'required|date',
            'notes' => 'nullable|string|max:255',
        ]);

        SalaryPayment::create([
            'shop_id' => $this->shopId(),
            'staff_id' => $staff->id,
            'amount' => $data['amount'],
            'paid_on' => $data['paid_on'],
            'notes' => $data['notes'] ?? null,
            'paid_by' => Auth::guard('admin')->id(),
        ]);

        return back()->with('status', 'Payment recorded for ' . $staff->name . '.');
    }

    public function destroyPayment(SalaryPayment $payment)
    {
        abort_unless($payment->shop_id === $this->shopId(), 403);
        $payment->delete();

        return back()->with('status', 'Payment removed.');
    }

    protected function shopId(): int
    {
        return Auth::guard('admin')->user()->shop_id;
    }
}
