<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\ClientModel;
use App\Models\CompanyModel;
use App\Models\InvoiceItemModel;
use App\Models\InvoiceModel;
use App\Models\PaymentModel;
use App\Models\ProductModel;
use App\Models\UserModel;
use Dompdf\Dompdf;
use Dompdf\Options;

class InvoiceController extends BaseController
{
    public function index()
    {
        $model = new InvoiceModel();
        $invoices = $model->forCompany($this->currentCompanyId())
            ->select('invoices.*, clients.name as client_name')
            ->join('clients', 'clients.id = invoices.client_id')
            ->orderBy('due_date', 'DESC')
            ->paginate(15);

        return view('admin/invoices/index', ['invoices' => $invoices, 'pager' => $model->pager]);
    }

    public function create()
    {
        $clients = (new ClientModel())->forCompany($this->currentCompanyId())->findAll();
        $products = (new ProductModel())->forCompany($this->currentCompanyId())->where('is_active', 1)->findAll();
        $invoiceModel = new InvoiceModel();
        $suggestedNumber = $invoiceModel->generateNumber($this->currentCompanyId());

        return view('admin/invoices/form', ['invoice' => null, 'items' => [], 'clients' => $clients, 'products' => $products, 'suggestedNumber' => $suggestedNumber, 'currencies' => $this->activeCurrencies()]);
    }

    public function store()
    {
        $model = new InvoiceModel();
        $data = $this->invoiceData();
        $data['company_id'] = $this->currentCompanyId();
        $data['created_by'] = session()->get('admin_user_id');

        $invoiceId = $model->insert($data);

        $this->saveItems($invoiceId);

        $this->logActivity('create_invoice', "أنشأ فاتورة رقم {$data['invoice_number']} بمبلغ {$data['amount']} {$data['currency']}");

        return redirect()->to('/admin/invoices')->with('message', lang('App.saved_successfully'));
    }

    public function edit($id)
    {
        $model = new InvoiceModel();
        $invoice = $model->forCompany($this->currentCompanyId())->find($id);
        if (! $invoice) return redirect()->to('/admin/invoices');

        $items = (new InvoiceItemModel())->where('invoice_id', $id)->findAll();
        $payments = (new PaymentModel())->where('invoice_id', $id)->findAll();
        $clients = (new ClientModel())->forCompany($this->currentCompanyId())->findAll();
        $products = (new ProductModel())->forCompany($this->currentCompanyId())->where('is_active', 1)->findAll();

        $currencies = $this->activeCurrencies();
        return view('admin/invoices/form', compact('invoice', 'items', 'clients', 'products', 'payments', 'currencies'));
    }

    public function update($id)
    {
        $data = $this->invoiceData();
        (new InvoiceModel())->update($id, $data);

        (new InvoiceItemModel())->where('invoice_id', $id)->delete();
        $this->saveItems($id);

        $this->logActivity('update_invoice', "عدّل فاتورة رقم {$data['invoice_number']}");

        return redirect()->to('/admin/invoices')->with('message', lang('App.saved_successfully'));
    }

    public function delete($id)
    {
        $invoice = (new InvoiceModel())->find($id);
        (new InvoiceModel())->delete($id);
        $this->logActivity('delete_invoice', "حذف فاتورة رقم " . ($invoice['invoice_number'] ?? $id));
        return redirect()->to('/admin/invoices')->with('message', lang('App.deleted_successfully'));
    }

    /** عرض الفاتورة بتصميم عصري داخل النظام */
    public function view($id)
    {
        $data = $this->invoiceDisplayData($id);
        if (! $data) return redirect()->to('/admin/invoices');

        return view('admin/invoices/view', $data);
    }

    /** تحميل نفس تصميم الفاتورة كملف PDF */
    public function downloadPdf($id)
    {
        $data = $this->invoiceDisplayData($id);
        if (! $data) return redirect()->to('/admin/invoices');

        $html = view('admin/invoices/pdf', $data);

        $options = new Options();
        $options->set('isRemoteEnabled', true);
        $options->set('defaultFont', 'DejaVu Sans');

        $dompdf = new Dompdf($options);
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        return $this->response
            ->setHeader('Content-Type', 'application/pdf')
            ->setHeader('Content-Disposition', 'attachment; filename="' . $data['invoice']['invoice_number'] . '.pdf"')
            ->setBody($dompdf->output());
    }

    /** تجميع كل بيانات الفاتورة اللازمة للعرض/PDF في مكان واحد */
    private function invoiceDisplayData($id): ?array
    {
        $invoice = (new InvoiceModel())->forCompany($this->currentCompanyId())->find($id);
        if (! $invoice) return null;

        $items = (new InvoiceItemModel())->where('invoice_id', $id)->findAll();
        $client = (new ClientModel())->find($invoice['client_id']);
        $company = (new CompanyModel())->find($invoice['company_id']);
        $creator = $invoice['created_by'] ? (new UserModel())->find($invoice['created_by']) : null;
        $paymentModel = new PaymentModel();
        $totalPaid = $paymentModel->completedTotal((int) $id);
        $pendingTotal = $paymentModel->pendingTotal((int) $id);

        return compact('invoice', 'items', 'client', 'company', 'creator', 'totalPaid', 'pendingTotal');
    }

    /** تسجيل دفعة جديدة على فاتورة - يحدث الحالة ويحسب العمولة تلقائياً */
    public function addPayment($invoiceId)
    {
        $paymentModel = new PaymentModel();
        $paymentModel->insert([
            'invoice_id' => $invoiceId,
            'amount' => $this->request->getPost('amount'),
            'currency' => $this->request->getPost('currency'),
            'payment_method' => $this->request->getPost('payment_method'),
            'status' => $this->request->getPost('status') ?: 'completed',
            'reference' => $this->request->getPost('reference'),
            'paid_at' => $this->request->getPost('paid_at') ?: date('Y-m-d'),
        ]);

        $paymentModel->afterPaymentCreated((int) $invoiceId);

        $invoice = (new InvoiceModel())->find($invoiceId);
        $this->logActivity('add_payment', "سجّل دفعة {$this->request->getPost('amount')} {$this->request->getPost('currency')} على فاتورة " . ($invoice['invoice_number'] ?? $invoiceId));

        return redirect()->to('/admin/invoices/' . $invoiceId . '/edit')->with('message', lang('App.payment_recorded'));
    }

    private function invoiceData(): array
    {
        return [
            'client_id' => $this->request->getPost('client_id'),
            'invoice_number' => $this->request->getPost('invoice_number'),
            'amount' => $this->request->getPost('amount'),
            'currency' => $this->request->getPost('currency'),
            'exchange_rate_at_creation' => $this->request->getPost('exchange_rate_at_creation') ?: 1,
            'issue_date' => $this->request->getPost('issue_date'),
            'due_date' => $this->request->getPost('due_date'),
            'status' => $this->request->getPost('status'),
            'notes' => $this->request->getPost('notes'),
        ];
    }

    private function saveItems($invoiceId): void
    {
        $descriptions = $this->request->getPost('item_description') ?? [];
        $amounts = $this->request->getPost('item_amount') ?? [];
        $productIds = $this->request->getPost('item_product_id') ?? [];
        $itemModel = new InvoiceItemModel();

        foreach ($descriptions as $i => $description) {
            if (! $description) continue;
            $itemModel->insert([
                'invoice_id' => $invoiceId,
                'product_id' => $productIds[$i] ?: null,
                'description' => $description,
                'amount' => $amounts[$i] ?? 0,
            ]);
        }
    }
}
