<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Models\Commission;
use App\Models\User;
use Illuminate\Http\Request;

class ReportController extends Controller
{
    public function dueBalances()
    {
        $reps = User::whereHas('role', function($q) {
            $q->where('name', 'Sales Representative');
        })->with(['vehicle'])->get();

        $customers = Customer::where('is_active', true)
            ->with(['sales', 'salesRep'])
            ->get();

        return view('admin.reports.due_balances', compact('customers', 'reps'));
    }

    public function commissions()
    {
        $reps = User::whereHas('role', function($q) {
            $q->where('name', 'Sales Representative');
        })->with(['role'])->get();

        $commissions = Commission::with(['salesRep', 'sale.customer'])
            ->latest()
            ->paginate(20);

        return view('admin.reports.commissions', compact('commissions', 'reps'));
    }
    public function cheques()
    {
        $cheques = \App\Models\Payment::where('method', 'Cheque')
            ->with(['customer', 'collector'])
            ->latest('created_at')
            ->paginate(20);

        return view('admin.reports.cheques', compact('cheques'));
    }

    public function updateChequeStatus(Request $request, $id)
    {
        $cheque = \App\Models\Payment::findOrFail($id);
        
        $request->validate([
            'status' => 'required|in:pending,cleared,returned'
        ]);

        $cheque->cheque_status = $request->status;
        $cheque->save();

        // Update linked commissions
        if ($request->status === 'cleared') {
            Commission::where('payment_id', $cheque->id)->update(['status' => 'approved']);
        } elseif ($request->status === 'returned') {
            Commission::where('payment_id', $cheque->id)->update(['status' => 'cancelled']);
            
            // Notify Rep logic here (Todo: Implement DatabaseNotification)
        }

        return redirect()->back()->with('success', 'Cheque status updated to ' . ucfirst($request->status));
    }
    public function cashCollections()
    {
        $collections = \App\Models\Payment::where('method', 'Cash')
            ->where('is_remitted', false)
            ->selectRaw('collected_by, sum(amount) as total_amount, count(id) as count')
            ->groupBy('collected_by')
            ->with(['collector'])
            ->get();
        
        // Append expenses to each collection
        foreach ($collections as $col) {
            $col->expenses = \App\Models\Expense::where('user_id', $col->collected_by)
                ->where('status', 'approved')
                ->where('is_reimbursed', false) // Use is_reimbursed here
                ->sum('amount');
            
            $col->net_handover = $col->total_amount - $col->expenses;
        }
            
        return view('admin.reports.cash_collections', compact('collections'));
    }

    public function markRemitted(Request $request)
    {
        $request->validate([
            'sales_rep_id' => 'required|exists:users,id',
            // 'amount' => 'required|numeric' // We will trust the ID and process pending
        ]);

        \Illuminate\Support\Facades\DB::transaction(function() use ($request) {
            // 1. Mark Payments as Remitted
            \App\Models\Payment::where('method', 'Cash')
                ->where('collected_by', $request->sales_rep_id)
                ->where('is_remitted', false)
                ->update(['is_remitted' => true]);

            // 2. Mark Expenses as Reimbursed (Deducted)
            \App\Models\Expense::where('user_id', $request->sales_rep_id)
                ->where('status', 'approved')
                ->where('is_reimbursed', false)
                ->update(['is_reimbursed' => true]);
        });

        return back()->with('success', 'Cash handed over and expenses deducted successfully.');
    }

    public function salesSummary(Request $request)
    {
        $salesBuilder = \App\Models\Sale::query();

        if ($request->filled('date_from')) {
            $salesBuilder->whereDate('created_at', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $salesBuilder->whereDate('created_at', '<=', $request->date_to);
        }
        if ($request->filled('sales_rep_id')) {
            $salesBuilder->where('sales_rep_id', $request->sales_rep_id);
        }

        // Clone for totals
        $totalsBuilder = clone $salesBuilder;
        $totalSales = $totalsBuilder->sum('net_total');
        $totalPaid = $totalsBuilder->sum('paid_amount');
        $totalBalance = $totalsBuilder->sum('balance_due');

        $sales = $salesBuilder->with(['customer', 'salesRep'])->latest()->paginate(20)->withQueryString();
        $reps = User::whereHas('role', function($q){ $q->where('name', 'Sales Representative'); })->get();

        return view('admin.reports.sales_summary', compact('sales', 'reps', 'totalSales', 'totalPaid', 'totalBalance'));
    }
}
