<?php

namespace App\Http\Controllers\Admin\Finance\Settlement;

use App\Http\Controllers\Controller;
use App\Models\MerchantDeduction;
use App\Models\User;
use Illuminate\Http\Request;

class DeductionController extends Controller
{
    public function __construct()
    {
        $this->middleware('can:finance.view')->only(['index', 'show']);
        $this->middleware('can:finance.add')->only(['create', 'store']);
        $this->middleware('can:finance.edit')->only(['edit', 'update', 'approve', 'reject', 'apply']);
        $this->middleware('can:finance.delete')->only(['destroy']);
    }
    public function index(Request $request)
    {
        $query = \App\Models\MerchantDeduction::with('merchant');

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('merchant_id')) {
            $query->where('merchant_id', $request->merchant_id);
        }
        if ($request->filled('start_date')) {
            $query->whereDate('deduction_date', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->whereDate('deduction_date', '<=', $request->end_date);
        }

        $deductions = $query->latest()->paginate(15);
        $merchants = \App\Models\User::where('role', 'seller')->get();

        $stats = [
            'total_pending' => \App\Models\MerchantDeduction::where('status', 'pending')->sum('amount'),
            'total_approved' => \App\Models\MerchantDeduction::where('status', 'approved')->sum('amount'),
            'total_applied' => \App\Models\MerchantDeduction::where('status', 'applied')->sum('amount'),
            'count_pending' => \App\Models\MerchantDeduction::where('status', 'pending')->count(),
        ];

        return view('admin.finance.settlements.deductions.index', compact('deductions', 'merchants', 'stats'));
    }

    public function create()
    {
        $merchants = \App\Models\User::where('role', 'seller')->orderBy('name')->get();
        return view('admin.finance.settlements.deductions.create', compact('merchants'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'merchant_id' => 'required|exists:users,id',
            'deduction_type' => 'required|string|max:255',
            'amount' => 'required|numeric|min:0.01',
            'deduction_date' => 'required|date',
            'description' => 'nullable|string',
        ]);

        \App\Models\MerchantDeduction::create(array_merge($validated, [
            'deduction_number' => 'DED-' . time(),
            'status' => 'approved',
        ]));

        return redirect()->route('finance.settlements.deductions.index')->with('success', 'Deduction created successfully.');
    }

    public function show(MerchantDeduction $deduction)
    {
        $deduction->load('merchant');
        return view('admin.finance.settlements.deductions.show', compact('deduction'));
    }

    public function edit(MerchantDeduction $deduction)
    {
        $merchants = \App\Models\User::where('role', 'seller')->orderBy('name')->get();
        return view('admin.finance.settlements.deductions.edit', compact('deduction', 'merchants'));
    }

    public function update(Request $request, MerchantDeduction $deduction)
    {
        $validated = $request->validate([
            'merchant_id' => 'required|exists:users,id',
            'deduction_type' => 'required|string|max:255',
            'amount' => 'required|numeric|min:0.01',
            'deduction_date' => 'required|date',
            'description' => 'nullable|string',
            'status' => 'required|in:pending,approved,rejected,applied',
        ]);

        $deduction->update($validated);

        return redirect()->route('finance.settlements.deductions.index')->with('success', 'Deduction updated successfully.');
    }

    public function destroy(MerchantDeduction $deduction)
    {
        $deduction->delete();
        return redirect()->route('finance.settlements.deductions.index')->with('success', 'Deduction deleted successfully.');
    }

    public function approve(MerchantDeduction $deduction)
    {
        $deduction->update(['status' => 'approved']);
        return back()->with('success', 'Deduction approved successfully.');
    }

    public function reject(MerchantDeduction $deduction)
    {
        $deduction->update(['status' => 'rejected']);
        return back()->with('success', 'Deduction rejected.');
    }

    public function apply(MerchantDeduction $deduction)
    {
        $deduction->update(['status' => 'applied']);
        return back()->with('success', 'Deduction applied successfully.');
    }
}
