<?php

namespace App\Http\Controllers;

use App\Models\Service;
use App\Models\SalesDashboard;
use App\Models\BankAccount;
use App\Models\DigitalPayment;
use App\Models\Customer;
use App\Models\Invoice;
use App\Models\InvoiceItem;
use App\Models\Transaction;
use App\Models\Quotation;
use Illuminate\Http\Request;

class ServiceSalesController extends Controller
{
    public function index()
    {
        // Get sales records that have service_id (service sales)
        $serviceSales = SalesDashboard::whereNotNull('service_id')
            ->orderBy('created_at', 'desc')
            ->get();

        return view('service-sales.index', compact('serviceSales'));
    }

    public function create()
    {
        $services = Service::orderBy('name', 'asc')->get();
        $customers = Customer::where('user_id', auth()->id())->orderBy('name', 'asc')->get();
        $bankAccounts = BankAccount::orderBy('bank_name', 'asc')->get();
        $digitalPayments = DigitalPayment::orderBy('provider', 'asc')->get();
        $quotations = Quotation::orderBy('quotation_number', 'desc')->get();

        return view('service-sales.create', compact('services', 'customers', 'bankAccounts', 'digitalPayments', 'quotations'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'date' => 'nullable|date',
            'customer_id' => 'required|exists:customers,id',
            'service_id' => 'required|exists:services,id',
            'qty' => 'nullable|integer|min:1',
            'sales' => 'required|numeric|min:0',
            'payment' => 'nullable|numeric|min:0',
            'payment_method' => 'nullable|in:cash,bank,digital',
            'bank_account_id' => 'required_if:payment_method,bank|nullable|exists:bank_accounts,id',
            'digital_payment_id' => 'required_if:payment_method,digital|nullable|exists:digital_payments,id',
            'quotation_id' => 'nullable|exists:quotations,id',
            'particulars' => 'nullable|string',
        ]);

        // Add user_id
        $validated['user_id'] = auth()->id();

        // Get service details
        $service = Service::findOrFail($validated['service_id']);

        // Calculate totals
        $qty = $validated['qty'] ?? 1;
        $totalSales = $qty * $validated['sales'];
        $cogs = $qty * ($service->cost_price ?? 0);
        $grossProfit = $totalSales - $cogs;
        $due = $totalSales - ($validated['payment'] ?? 0);

        // Determine invoice status
        $status = 'unpaid';
        if (($validated['payment'] ?? 0) > 0 && ($validated['payment'] ?? 0) >= $totalSales) {
            $status = 'paid';
        } elseif (($validated['payment'] ?? 0) > 0 && ($validated['payment'] ?? 0) < $totalSales) {
            $status = 'partial';
        }

        // Create Invoice
        $invoice = Invoice::create([
            'user_id' => auth()->id(),
            'customer_id' => $validated['customer_id'],
            'date' => $validated['date'] ?? now(),
            'status' => $status,
            'notes' => $validated['particulars'] ?? 'Service Sale',
            'subtotal' => $totalSales,
            'tax' => 0,
            'discount' => 0,
            'total' => $totalSales,
            'paid' => $validated['payment'] ?? 0,
            'due' => max(0, $due),
        ]);

        // Create Invoice Item for Service
        InvoiceItem::create([
            'invoice_id' => $invoice->id,
            'service_id' => $service->id,
            'quantity' => $qty,
            'unit_price' => $validated['sales'],
            'total' => $totalSales,
            'purchase_price' => $service->cost_price ?? 0,
            'cogs' => $cogs,
            'profit' => $grossProfit,
        ]);

        // Process payment if applicable
        if (($validated['payment'] ?? 0) > 0) {
            $this->processPayment($validated, $invoice);
        }

        // Create Sales Dashboard Record
        SalesDashboard::create([
            'user_id' => auth()->id(),
            'date' => $validated['date'] ?? now(),
            'customer_id' => $validated['customer_id'],
            'service_id' => $service->id,
            'qty' => $qty,
            'sales' => $totalSales,
            'payment' => $validated['payment'] ?? 0,
            'payment_method' => $validated['payment_method'] ?? null,
            'bank_account_id' => $validated['bank_account_id'] ?? null,
            'digital_payment_id' => $validated['digital_payment_id'] ?? null,
            'due' => max(0, $due),
            'cogs' => $cogs,
            'gross_profit' => $grossProfit,
            'particulars' => $validated['particulars'] ?? 'Service: ' . $service->name,
            'invoice_id' => $invoice->id,
        ]);

        // Update quotation status to 'sale' if quotation_id is provided
        if (!empty($validated['quotation_id'])) {
            $quotation = Quotation::find($validated['quotation_id']);
            if ($quotation) {
                $quotation->update(['status' => 'sale']);
            }
        }

        return redirect()->route('service-sales.index')
            ->with('success', 'Service sale created successfully. Invoice generated.');
    }

    public function edit(SalesDashboard $serviceSale)
    {
        $services = Service::orderBy('name', 'asc')->get();
        $customers = Customer::where('user_id', auth()->id())->orderBy('name', 'asc')->get();
        $bankAccounts = BankAccount::orderBy('bank_name', 'asc')->get();
        $digitalPayments = DigitalPayment::orderBy('provider', 'asc')->get();
        $quotations = Quotation::orderBy('quotation_number', 'desc')->get();

        return view('service-sales.edit', compact('serviceSale', 'services', 'customers', 'bankAccounts', 'digitalPayments', 'quotations'));
    }

    public function update(Request $request, SalesDashboard $serviceSale)
    {
        $validated = $request->validate([
            'date' => 'nullable|date',
            'customer_id' => 'required|exists:customers,id',
            'service_id' => 'required|exists:services,id',
            'qty' => 'nullable|integer|min:1',
            'sales' => 'required|numeric|min:0',
            'payment' => 'nullable|numeric|min:0',
            'payment_method' => 'nullable|in:cash,bank,digital',
            'bank_account_id' => 'required_if:payment_method,bank|nullable|exists:bank_accounts,id',
            'digital_payment_id' => 'required_if:payment_method,digital|nullable|exists:digital_payments,id',
            'quotation_id' => 'nullable|exists:quotations,id',
            'particulars' => 'nullable|string',
        ]);

        // Get service details
        $service = Service::findOrFail($validated['service_id']);

        // Calculate totals
        $qty = $validated['qty'] ?? 1;
        $totalSales = $qty * $validated['sales'];
        $cogs = $qty * ($service->cost_price ?? 0);
        $grossProfit = $totalSales - $cogs;
        $due = $totalSales - ($validated['payment'] ?? 0);

        // Determine invoice status
        $status = 'unpaid';
        if (($validated['payment'] ?? 0) > 0 && ($validated['payment'] ?? 0) >= $totalSales) {
            $status = 'paid';
        } elseif (($validated['payment'] ?? 0) > 0 && ($validated['payment'] ?? 0) < $totalSales) {
            $status = 'partial';
        }

        // Update Invoice if exists
        if ($serviceSale->invoice_id) {
            $invoice = Invoice::find($serviceSale->invoice_id);
            if ($invoice) {
                $invoice->update([
                    'customer_id' => $validated['customer_id'],
                    'date' => $validated['date'] ?? now(),
                    'status' => $status,
                    'notes' => $validated['particulars'] ?? 'Service Sale',
                    'total' => $totalSales,
                    'paid' => $validated['payment'] ?? 0,
                    'due' => max(0, $due),
                ]);

                // Update Invoice Item
                $invoice->items()->whereNotNull('service_id')->delete();
                InvoiceItem::create([
                    'invoice_id' => $invoice->id,
                    'service_id' => $service->id,
                    'quantity' => $qty,
                    'unit_price' => $validated['sales'],
                    'total' => $totalSales,
                    'purchase_price' => $service->cost_price ?? 0,
                    'cogs' => $cogs,
                    'profit' => $grossProfit,
                ]);
            }
        }

        // Update Sales Dashboard Record
        $serviceSale->update([
            'date' => $validated['date'] ?? now(),
            'customer_id' => $validated['customer_id'],
            'service_id' => $service->id,
            'qty' => $qty,
            'sales' => $totalSales,
            'payment' => $validated['payment'] ?? 0,
            'payment_method' => $validated['payment_method'] ?? null,
            'bank_account_id' => $validated['bank_account_id'] ?? null,
            'digital_payment_id' => $validated['digital_payment_id'] ?? null,
            'due' => max(0, $due),
            'cogs' => $cogs,
            'gross_profit' => $grossProfit,
            'particulars' => $validated['particulars'] ?? 'Service: ' . $service->name,
        ]);

        // Update quotation status to 'sale' if quotation_id is provided
        if (!empty($validated['quotation_id'])) {
            $quotation = Quotation::find($validated['quotation_id']);
            if ($quotation) {
                $quotation->update(['status' => 'sale']);
            }
        }

        return redirect()->route('service-sales.index')
            ->with('success', 'Service sale updated successfully.');
    }

    public function destroy(SalesDashboard $serviceSale)
    {
        // Delete linked invoice if exists
        if ($serviceSale->invoice_id) {
            $invoice = Invoice::find($serviceSale->invoice_id);
            if ($invoice) {
                $invoice->delete();
            }
        }

        $serviceSale->delete();

        return redirect()->route('service-sales.index')
            ->with('success', 'Service sale deleted successfully.');
    }

    protected function processPayment($validated, $invoice)
    {
        // If payment_method is not specified but payment exists, default to cash
        $paymentMethod = $validated['payment_method'] ?? 'cash';

        if ($paymentMethod === 'bank') {
            $bankAccount = BankAccount::findOrFail($validated['bank_account_id']);
            $balanceBefore = $bankAccount->balance;
            $bankAccount->update(['balance' => $bankAccount->balance + $validated['payment']]);

            Transaction::create([
                'user_id' => auth()->id(),
                'date' => $validated['date'] ?? now(),
                'type' => 'income',
                'details' => 'Service Payment: ' . ($invoice->invoice_no ?? 'N/A'),
                'payment_method' => 'bank',
                'bank_account_id' => $bankAccount->id,
                'amount' => $validated['payment'],
                'balance_before' => $balanceBefore,
                'balance_after' => $bankAccount->balance,
                'reference' => 'Service Payment',
                'notes' => 'Payment received for service sale. Invoice: ' . ($invoice->invoice_no ?? 'N/A')
            ]);

        } elseif ($paymentMethod === 'digital') {
            $digitalPayment = DigitalPayment::findOrFail($validated['digital_payment_id']);
            $balanceBefore = $digitalPayment->balance;
            $digitalPayment->update(['balance' => $digitalPayment->balance + $validated['payment']]);

            Transaction::create([
                'user_id' => auth()->id(),
                'date' => $validated['date'] ?? now(),
                'type' => 'income',
                'details' => 'Service Payment: ' . ($invoice->invoice_no ?? 'N/A'),
                'payment_method' => 'digital',
                'digital_payment_id' => $digitalPayment->id,
                'amount' => $validated['payment'],
                'balance_before' => $balanceBefore,
                'balance_after' => $digitalPayment->balance,
                'reference' => 'Service Payment',
                'notes' => 'Payment received for service sale. Invoice: ' . ($invoice->invoice_no ?? 'N/A')
            ]);

        } else {
            // Default to cash
            // For cash, we don't need a bank account, just record the transaction
            Transaction::create([
                'user_id' => auth()->id(),
                'date' => $validated['date'] ?? now(),
                'type' => 'income',
                'details' => 'Service Payment (Cash): ' . ($invoice->invoice_no ?? 'N/A'),
                'payment_method' => 'cash',
                'amount' => $validated['payment'],
                'balance_before' => 0, // Not applicable for cash
                'balance_after' => 0, // Not applicable for cash
                'reference' => 'Service Payment',
                'notes' => 'Cash payment received for service sale. Invoice: ' . ($invoice->invoice_no ?? 'N/A')
            ]);
        }
    }
}

