<?php

namespace Modules\POS\Controllers;

use core\Controller;
use core\Auth;
use core\Database;
use core\Session;
use core\Security;
use Modules\POS\Models\Invoice;

class InvoiceController extends Controller
{
    private Invoice $invoiceModel;

    public function __construct()
    {
        parent::__construct();
        $this->invoiceModel = new Invoice();
    }

    public function index(): void
    {
        $this->requirePermission('invoices_view');

        $db = Database::getInstance();
        $dateFrom = $this->request->get('date_from', '');
        $dateTo = $this->request->get('date_to', '');
        $status = $this->request->get('status', '');
        $customerId = $this->request->get('customer_id', '');
        $search = $this->request->get('search', '');
        $page = max(1, (int)$this->request->get('page', 1));
        $perPage = PAGINATION_LIMIT;

        $query = $db->table('invoices i')
            ->select('i.*, c.first_name as customer_first_name, c.last_name as customer_last_name,
                      c.phone as customer_phone')
            ->leftJoin('customers c', 'i.customer_id', '=', 'c.id')
            ->where('i.deleted_at', 'IS', null);

        if (!empty($dateFrom)) {
            $query->where('i.created_at', '>=', $dateFrom . ' 00:00:00');
        }
        if (!empty($dateTo)) {
            $query->where('i.created_at', '<=', $dateTo . ' 23:59:59');
        }
        if (!empty($status)) {
            $query->where('i.payment_status', $status);
        }
        if (!empty($customerId)) {
            $query->where('i.customer_id', (int)$customerId);
        }
        if (!empty($search)) {
            $query->where(function ($q) use ($search) {
                $term = '%' . $search . '%';
                $q->where('i.invoice_number', 'LIKE', $term)
                  ->orWhere('c.first_name', 'LIKE', $term)
                  ->orWhere('c.last_name', 'LIKE', $term)
                  ->orWhere('c.phone', 'LIKE', $term);
            });
        }

        $invoices = $query->orderBy('i.created_at', 'DESC')
            ->paginate($perPage, $page);

        $customers = $db->table('customers')
            ->where('deleted_at', 'IS', null)
            ->orderBy('first_name', 'ASC')
            ->get();

        $this->view('POS/index', [
            'title' => 'Invoices',
            'breadcrumb' => ['Invoices' => url('invoices')],
            'invoices' => $invoices,
            'dateFrom' => $dateFrom,
            'dateTo' => $dateTo,
            'status' => $status,
            'customerId' => $customerId,
            'search' => $search,
            'customers' => $customers,
        ]);
    }

    public function show(int $id): void
    {
        $this->requirePermission('invoices_view');

        $db = Database::getInstance();
        $invoice = $db->query(
            "SELECT i.*, c.first_name as customer_first_name, c.last_name as customer_last_name,
                    c.email as customer_email, c.phone as customer_phone, c.address as customer_address,
                    u.first_name as user_first_name, u.last_name as user_last_name,
                    b.name as branch_name, b.address as branch_address, b.phone as branch_phone, b.email as branch_email
             FROM invoices i
             LEFT JOIN customers c ON i.customer_id = c.id
             LEFT JOIN users u ON i.created_by = u.id
             LEFT JOIN branches b ON i.branch_id = b.id
             WHERE i.id = :id AND i.deleted_at IS NULL",
            [':id' => $id]
        );

        if (empty($invoice)) {
            $this->redirectWith(url('invoices'), 'error', 'Invoice not found.');
        }
        $invoice = $invoice[0];

        $items = $db->table('invoice_items')
            ->where('invoice_id', $id)
            ->get();

        $payments = $db->table('invoice_payments')
            ->where('invoice_id', $id)
            ->get();

        $this->view('POS/invoice', [
            'title' => 'Invoice #' . $invoice->invoice_number,
            'breadcrumb' => [
                'Invoices' => url('invoices'),
                '#' . $invoice->invoice_number => url('invoices/' . $id),
            ],
            'invoice' => $invoice,
            'items' => $items,
            'payments' => $payments,
        ]);
    }

    public function printInvoice(int $id): void
    {
        $this->requirePermission('invoices_view');

        $db = Database::getInstance();
        $invoice = $db->query(
            "SELECT i.*, c.first_name as customer_first_name, c.last_name as customer_last_name,
                    c.email as customer_email, c.phone as customer_phone, c.address as customer_address,
                    u.first_name as user_first_name, u.last_name as user_last_name,
                    b.name as branch_name, b.address as branch_address, b.phone as branch_phone, b.email as branch_email
             FROM invoices i
             LEFT JOIN customers c ON i.customer_id = c.id
             LEFT JOIN users u ON i.created_by = u.id
             LEFT JOIN branches b ON i.branch_id = b.id
             WHERE i.id = :id AND i.deleted_at IS NULL",
            [':id' => $id]
        );

        if (empty($invoice)) {
            $this->redirectWith(url('invoices'), 'error', 'Invoice not found.');
        }
        $invoice = $invoice[0];

        $items = $db->table('invoice_items')
            ->where('invoice_id', $id)
            ->get();

        $payments = $db->table('invoice_payments')
            ->where('invoice_id', $id)
            ->get();

        $this->view('POS/print_invoice', [
            'title' => 'Print Invoice #' . $invoice->invoice_number,
            'invoice' => $invoice,
            'items' => $items,
            'payments' => $payments,
        ], 'none');
    }
}
