<?php

namespace App\Http\Controllers\Accounting;

use App\Http\Controllers\Controller;
use App\Models\SalesPerson;
use App\Models\SalesCommission;
use App\Models\SalesCommissionPayment;
use App\Models\FinancialTreasury;
use App\Services\WaSenderService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

use App\Models\FinancialTransaction;

class SalesPersonController extends Controller
{
    protected $waSender;

    public function __construct(WaSenderService $waSender)
    {
        $this->waSender = $waSender;
    }

    public function index()
    {
        $salesPeople = SalesPerson::withCount([
            'commissions' => function ($q) {
                $q->where('status', '!=', 'paid');
            }
        ])->get();
        return view('accounting.sales_people.index', compact('salesPeople'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'nullable|string|max:20',
            'whatsapp' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
        ]);

        SalesPerson::create($validated);

        return back()->with('success', 'Sales person added successfully.');
    }

    public function edit(SalesPerson $salesPerson)
    {
        return view('accounting.sales_people.edit', compact('salesPerson'));
    }

    public function update(Request $request, SalesPerson $salesPerson)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'nullable|string|max:20',
            'whatsapp' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
            'is_active' => 'boolean',
        ]);

        $salesPerson->update($validated);

        return redirect()->route('accounting.sales-people.index')->with('success', 'Sales person updated successfully.');
    }

    public function destroy(SalesPerson $salesPerson)
    {
        if ($salesPerson->commissions()->count() > 0) {
            return back()->with('error', 'Cannot delete sales person with existing commissions. Deactivate them instead.');
        }

        $salesPerson->delete();
        return redirect()->route('accounting.sales-people.index')->with('success', 'Sales person deleted successfully.');
    }

    public function show(SalesPerson $salesPerson)
    {
        $salesPerson->load(['commissions.invoice', 'payments.treasury']);
        $treasuries = FinancialTreasury::where('is_active', true)->get();
        return view('accounting.sales_people.show', compact('salesPerson', 'treasuries'));
    }

    public function storePayment(Request $request, SalesPerson $salesPerson)
    {
        $validated = $request->validate([
            'amount' => 'required|numeric|min:0.01',
            'date' => 'required|date',
            'treasury_id' => 'required|exists:financial_treasuries,id',
            'notes' => 'nullable|string',
        ]);

        $treasury = FinancialTreasury::find($validated['treasury_id']);
        if ($treasury->balance < $validated['amount']) {
            return back()->with('error', 'Insufficient balance in the selected treasury.');
        }

        $payment = $salesPerson->payments()->create([
            'amount' => $validated['amount'],
            'date' => $validated['date'],
            'treasury_id' => $validated['treasury_id'],
            'notes' => $validated['notes'],
            'user_id' => Auth::id(),
            'payment_method' => 'cash',
        ]);

        // Record as a General Financial Transaction
        $payment->transactions()->create([
            'treasury_id' => $validated['treasury_id'],
            'user_id' => Auth::id(),
            'type' => 'out',
            'amount' => $validated['amount'],
            'date' => $validated['date'],
            'description' => "Commission Payout to {$salesPerson->name} (Payment #{$payment->id})",
            'ref_no' => 'COMM-' . str_pad($payment->id, 5, '0', STR_PAD_LEFT)
        ]);

        // Update treasury balance
        $treasury->decrement('balance', $validated['amount']);

        // Update commission statuses (simplistic: marking pending ones as paid if amount covers them)
        // In a real system, you might want more granular tracking.
        $this->updateCommissionStatuses($salesPerson);

        // Notify via WhatsApp
        $this->notifyPayment($payment);

        return back()->with('success', 'Payment recorded successfully.');
    }

    protected function updateCommissionStatuses(SalesPerson $salesPerson)
    {
        $totalPaid = $salesPerson->payments()->sum('amount');
        $commissions = $salesPerson->commissions()->orderBy('created_at')->get();

        $runningTotal = 0;
        foreach ($commissions as $commission) {
            $runningTotal += $commission->amount;
            if ($totalPaid >= $runningTotal) {
                $commission->update(['status' => 'paid']);
            } elseif ($totalPaid > ($runningTotal - $commission->amount)) {
                $commission->update(['status' => 'partial']);
            } else {
                $commission->update(['status' => 'pending']);
            }
        }
    }

    protected function notifyPayment(SalesCommissionPayment $payment)
    {
        $salesPerson = $payment->salesPerson;
        $phone = $salesPerson->whatsapp ?: $salesPerson->phone;

        if (!$phone)
            return;

        $message = "تم صرف دفعة من عمولاتك بقيمة: " . number_format($payment->amount, 2) . " ج.م\n";
        $message .= "التاريخ: " . (\Carbon\Carbon::parse($payment->date)->format('Y-m-d')) . "\n";
        $message .= "المتبقي لك: " . number_format($salesPerson->balance, 2) . " ج.م\n";
        $message .= "شكراً لجهودك!";

        try {
            $this->waSender->sendMessage($phone, $message);
        } catch (\Exception $e) {
            // Log error
        }
    }

    public function printPayment(SalesCommissionPayment $payment)
    {
        $payment->load(['salesPerson', 'treasury']);
        $settings = \App\Models\Setting::getGroup('general');
        return view('accounting.sales_people.print_payment', compact('payment', 'settings'));
    }

    public function printStatement(SalesPerson $salesPerson)
    {
        $salesPerson->load(['commissions.invoice', 'payments.treasury']);
        $settings = \App\Models\Setting::getGroup('general');
        return view('accounting.sales_people.print_statement', compact('salesPerson', 'settings'));
    }

    public function deletePayment(SalesCommissionPayment $payment)
    {
        $salesPerson = $payment->salesPerson;
        $treasury = $payment->treasury;

        // Refund treasury
        $treasury->increment('balance', $payment->amount);

        // Delete associated financial transactions
        $payment->transactions()->delete();

        $payment->delete();

        // Recalculate statuses
        $this->updateCommissionStatuses($salesPerson);

        return back()->with('success', 'Payment reversed successfully.');
    }
}
