<?php

class InvoiceController extends Controller
{
    private $invoiceModel;

    public function __construct(){
        $this->invoiceModel = $this->model('Invoice');
        $this->customerModel = $this->model('Customer');
        $this->productModel = $this->model('Product');
    
    }

    // List invoices
public function index(){
    if (session_status() === PHP_SESSION_NONE) session_start();
    
    $userId = $_SESSION['user_id'];
    $role   = $_SESSION['user_role'] ?? 'agent';

    $limit       = 10;
    $currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $offset      = ($currentPage - 1) * $limit;

    // Capture filters from GET
    $filters = [
        'id'           => $_GET['id'] ?? '',
        'customer'     => $_GET['customer'] ?? '',
        'status'       => $_GET['status'] ?? '',
        'invoice_type' => $_GET['invoice_type'] ?? '',
        'due_date'     => $_GET['due_date'] ?? ''
    ];

    // Get filtered invoices
    $invoices = $this->invoiceModel->getInvoicesPaginatedFiltered($userId, $role, $limit, $offset, $filters);

    // Count total (for pagination) with filters
    $totalInvoices = $this->invoiceModel->countInvoicesFiltered($userId, $role, $filters);
    $totalPages = ceil($totalInvoices / $limit);

    $this->view('invoices/index', [
        'invoices'    => $invoices,
        'currentPage' => $currentPage,
        'totalPages'  => $totalPages,
        'role'        => $role,
        'filters'     => $filters
    ]);
}



    // Add invoice
    public function add(){
    
    if (session_status() === PHP_SESSION_NONE) session_start();
    // Load customers and products for the form dropdowns
    $userId = $_SESSION['user_id'];
    $role = $_SESSION['user_role'];
    
    $customers = $this->customerModel->getAllCustomers();
    $products = $this->productModel->getAllProduct();

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Sanitize & collect posted data
        $customer_id = $_POST['customer_id'] ?? null;

        $customerData = [
            'user_id' => $_SESSION['user_id'],
            'name' => trim($_POST['customer_name']),
            'email' => trim($_POST['customer_email']),
            'phone' => trim($_POST['customer_phone']),
            'address_1' => trim($_POST['address_1']),
            'address_2' => trim($_POST['address_2']),
            'city' => trim($_POST['city']),
            'country' => trim($_POST['country']),
            'postcode' => trim($_POST['postcode']),
            'unit_number' => trim($_POST['unit_number']),
        ];

        // Create new customer if no customer_id provided
        if (empty($customer_id)) {
            $customer_id = $this->customerModel->addCustomer($customerData);
            if (!$customer_id) {
                $_SESSION['error'] = 'Failed to create customer.';
                $this->view('invoices/add', ['customers' => $customers, 'products' => $products]);
                return;
            }
        }

        // Invoice fields
        $invoiceData = [
            'customer_id' => $customer_id,
            'invoice_date' => $_POST['invoice_date'] ?? date('Y-m-d'),
            'due_date' => $_POST['due_date'] ?? date('Y-m-d'),
            'discount' => floatval($_POST['discount'] ?? 0),
            'shipping' => floatval($_POST['shipping'] ?? 0),
            'tax' => floatval($_POST['tax'] ?? 0),
            'status' => $_POST['status'] ?? 'Pending',
            'notes' => trim($_POST['notes'] ?? ''),
            'invoice_type' => trim($_POST['invoice_type'] ?? 'Invoice'),
        ];

        // Add invoice and get invoice_id
        $invoice_id = $this->invoiceModel->addInvoice($invoiceData);
        if (!$invoice_id) {
            $_SESSION['error'] = 'Failed to create invoice.';
            $this->view('invoices/add', ['customers' => $customers, 'products' => $products]);
            return;
        }

        // Process invoice items
        $product_ids = $_POST['product_id'] ?? [];
        $product_names = $_POST['product_name'] ?? [];
        $product_prices = $_POST['product_price'] ?? [];
        $product_qtys = $_POST['product_qty'] ?? [];
        $product_discounts = $_POST['product_discount'] ?? [];

        foreach ($product_names as $index => $name) {
            $name = trim($name);
            $qty = intval($product_qtys[$index] ?? 1);
            $price = floatval($product_prices[$index] ?? 0);
            $discount = floatval($product_discounts[$index] ?? 0);

            if (empty($name) || $qty <= 0 || $price < 0 || $discount < 0) {
                continue; // skip invalid rows
            }

            $itemData = [
                'invoice_id' => $invoice_id,
                'product_id' => !empty($product_ids[$index]) ? intval($product_ids[$index]) : null,
                'product_name' => $name,
                'quantity' => $qty,
                'price' => $price,
                'discount' =>  $discount,
                'total' => ($price - $discount) * $qty,
            ];

            $this->invoiceModel->addInvoiceItem($itemData);
        }

        $_SESSION['success'] = 'Invoice created successfully.';
        header('Location: ' . BASE_URL . '/invoice');
        exit;
    }

    $this->view('invoices/add', ['customers' => $customers, 'products' => $products]);
}

    // Edit invoice
    public function edit($id) {
    if (session_status() === PHP_SESSION_NONE) session_start();

    if (!isset($_SESSION['user_id'])) {
        header("Location: " . BASE_URL . "/login");
        exit;
    }

    $invoiceModel = $this->model('Invoice');
    $customerModel = $this->model('Customer');
    $productModel = $this->model('Product');

    $invoice = $invoiceModel->getInvoiceById($id);
    if (!$invoice) {
        $_SESSION['error'] = "Invoice not found.";
        header("Location: " . BASE_URL . "/invoice");
        exit;
    }

    // Get current customer info
    $customer = $customerModel->getCustomerById($invoice['customer_id']);

    // Get customers list for dropdown
    $userId = $_SESSION['user_id'];
    $role = $_SESSION['user_role'];
    $customers = $customerModel->getCustomersPaginated($userId, $role, 1000, 0);
    $invoiceItems = $invoiceModel->getInvoiceItemsByInvoiceId($id);
    $products = $productModel->getAllProduct();

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Update customer info first
        $customerData = [
            'user_id' => $_SESSION['user_id'],
            'name'        => trim($_POST['customer_name']        ?? ($customer['name']        ?? '')),
    'email'       => trim($_POST['customer_email']       ?? ($customer['email']       ?? '')),
    'phone'       => trim($_POST['customer_phone']       ?? ($customer['phone']       ?? '')),
    'company'     => trim($_POST['customer_company']     ?? ($customer['company']     ?? '')),
    'address_1'   => trim($_POST['customer_address_1']   ?? ($customer['address_1']   ?? '')),
    'address_2'   => trim($_POST['customer_address_2']   ?? ($customer['address_2']   ?? '')),
    'city'        => trim($_POST['customer_city']        ?? ($customer['city']        ?? '')),
    'country'     => trim($_POST['customer_country']     ?? ($customer['country']     ?? '')),
    'postcode'    => trim($_POST['customer_postcode']    ?? ($customer['postcode']    ?? '')),
    'unit_number' => trim($_POST['customer_unit_number'] ?? ($customer['unit_number'] ?? '')),
        ];

        // If user changed the selected customer in dropdown, update the invoice's customer_id
        $newCustomerId = intval($_POST['existing_customer'] ?? $invoice['customer_id']);
        if ($newCustomerId !== $invoice['customer_id']) {
            $invoice['customer_id'] = $newCustomerId;
        }

        // Update customer info in DB (for current or newly selected customer)
        $customerModel->updateCustomer($invoice['customer_id'], $customerData);
        
        

        // Prepare invoice data
           // Update invoice info
       $invoiceData = [
            'customer_id' => $_POST['customer_id'],
            'invoice_date' => $_POST['invoice_date'] ?? date('Y-m-d'),
            'due_date' => $_POST['due_date'] ?? date('Y-m-d'),
            'discount' => floatval($_POST['discount'] ?? 0),
            'shipping' => floatval($_POST['shipping'] ?? 0),
            'tax' => floatval($_POST['tax'] ?? 0),
            'status' => $_POST['status'] ?? 'Pending',
            'notes' => trim($_POST['notes'] ?? ''),
            'invoice_type' => trim($_POST['invoice_type'] ?? 'Invoice'),
        ];

    
        if ($invoiceModel->updateInvoice($id, $invoiceData)) {
    
            // Remove old items
            $invoiceModel->deleteInvoiceItemsByInvoiceId($id);
            
            // Add updated items
            if (!empty($_POST['product_name'])) {
    // Make sure $product_ids exists
    $product_ids = $_POST['product_id'] ?? [];

    foreach ($_POST['product_name'] as $index => $name) {
        $name = trim($name);
        if ($name === '') continue;

        $itemData = [
            'invoice_id'   => $id,
            'product_id'   => isset($product_ids[$index]) && $product_ids[$index] !== '' ? intval($product_ids[$index]) : null,
            'product_name' => $name,
            'quantity'     => isset($_POST['quantity'][$index]) ? (float)$_POST['quantity'][$index] : 0,
            'price'        => isset($_POST['price'][$index]) ? (float)$_POST['price'][$index] : 0,
            'discount'     => isset($_POST['discount'][$index]) ? (float)$_POST['discount'][$index] : 0,
            'tax'          => isset($_POST['tax'][$index]) ? (float)$_POST['tax'][$index] : 0,
            'total'        => isset($_POST['total'][$index]) ? (float)$_POST['total'][$index] : 0
        ];

        $invoiceModel->addInvoiceItem($itemData);
    }
}

    
            $_SESSION['success'] = "Invoice updated successfully.";
            header("Location: " . BASE_URL . "/invoice");
            exit;
        } else {
            $error = "Failed to update invoice.";
            $this->view('invoices/edit', compact('invoice', 'customer', 'customers', 'invoiceItems', 'error'));
            return;
        }
    }
    
    $this->view('invoices/edit', compact('invoice', 'customer', 'customers', 'invoiceItems', 'products'));
}

    // Delete invoice
    public function delete($id){
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
    
        if ($this->invoiceModel->deleteInvoice($id)) {
            $_SESSION['success'] = "Invoice deleted successfully.";
        } else {
            $_SESSION['error'] = "Error deleting invoice.";
        }
    
        header("Location: " . BASE_URL . "/invoice");
        exit; // 🔹 Always exit after redirect
    }
    
    // In your InvoiceController.php
    public function download($id) {
    if (session_status() === PHP_SESSION_NONE) session_start();

    $invoice = $this->invoiceModel->getInvoiceById($id);
    if (!$invoice) {
        $_SESSION['error'] = "Invoice not found.";
        header("Location: " . BASE_URL . "/invoice");
        exit;
    }

    $customer = $this->customerModel->getCustomerById($invoice['customer_id']);
    $items = $this->invoiceModel->getInvoiceItemsByInvoiceId($id);

    require_once __DIR__ . '../../../vendor/InvoicePDF.php';

    if (ob_get_length()) ob_end_clean();

    $pdf = new InvoicePDF('P', 'mm', 'A4', true, 'UTF-8', false);
    $pdf->SetCreator('TechLutry PTY LTD');
    $pdf->SetAuthor('TechLutry PTY LTD');
    $pdf->SetTitle('Invoice #'.$invoice['id']);
    $pdf->SetSubject('Invoice');

    $pdf->SetMargins(15, 45, 15); // Left, Top, Right
    $pdf->SetHeaderMargin(10);
    $pdf->SetFooterMargin(25);

    $pdf->AddPage();

    // Customer details and invoice info
    $pdf->CustomerDetails($customer, $invoice);

    // Invoice table with optional discount & tax
    $discount = floatval($invoice['discount'] ?? 0);
    $tax = floatval($invoice['tax'] ?? 0);
    $pdf->InvoiceTable($items, $discount, $tax);

    // Open in browser tab
    $pdf->Output('INVOICE_' . $invoice['id'] . '.pdf', 'I'); // 'I' = inline
    exit;
}

    public function downloadTaxInvoice($id) {
    if (session_status() === PHP_SESSION_NONE) session_start();

    $invoice = $this->invoiceModel->getInvoiceById($id);
    if (!$invoice) {
        $_SESSION['error'] = "Invoice not found.";
        header("Location: " . BASE_URL . "/invoice");
        exit;
    }

    $customer = $this->customerModel->getCustomerById($invoice['customer_id']);
    $items = $this->invoiceModel->getInvoiceItemsByInvoiceId($id);

    require_once __DIR__ . '../../../vendor/TaxInvoicePDF.php';

    if (ob_get_length()) ob_end_clean();

    $pdf = new TaxInvoicePDF('P', 'mm', 'A4', true, 'UTF-8', false);
    $pdf->SetCreator('TechLutry PTY LTD');
    $pdf->SetAuthor('TechLutry PTY LTD');
    $pdf->SetTitle('Tax Invoice #'.$invoice['id']);
    $pdf->SetSubject('Tax Invoice');

    $pdf->SetMargins(15, 45, 15);
    $pdf->SetHeaderMargin(10);
    $pdf->SetFooterMargin(25);

    $pdf->AddPage();

    $pdf->CustomerDetails($customer, $invoice);

    $discount = floatval($invoice['discount'] ?? 0);
    $tax = floatval($invoice['tax'] ?? 15); // default 15% VAT in SA
    $pdf->InvoiceTable($items, $discount, $tax);

    $pdf->Output('TAX_INVOICE_' . $invoice['id'] . '.pdf', 'I');
    exit;
}

public function downloadDeliveryNote($invoiceId) {
    if (session_status() === PHP_SESSION_NONE) session_start();

    $invoice = $this->invoiceModel->getInvoiceById($invoiceId);
    if (!$invoice) {
        $_SESSION['error'] = "Invoice not found.";
        header("Location: " . BASE_URL . "/invoice");
        exit;
    }

    $customer = $this->customerModel->getCustomerById($invoice['customer_id']);
    $items = $this->invoiceModel->getInvoiceItemsByInvoiceId($invoiceId);

    require_once __DIR__ . '../../../vendor/DeliveryNotePDF.php';
    if (ob_get_length()) ob_end_clean();

    $pdf = new DeliveryNotePDF('P', 'mm', 'A4', true, 'UTF-8', false);
    $pdf->SetCreator('TechLutry PTY LTD');
    $pdf->SetAuthor('TechLutry PTY LTD');
    $pdf->SetTitle('Delivery Note #'.$invoice['id']);
    $pdf->SetSubject('Delivery Note');

    $pdf->SetMargins(15, 45, 15);
    $pdf->SetHeaderMargin(10);
    $pdf->SetFooterMargin(25);

    $pdf->AddPage();
    $pdf->CustomerDetails($customer, $invoice); // use invoice as delivery reference
    $pdf->ItemsTable($items);

    $pdf->Output('DELIVERY_NOTE_' . $invoice['id'] . '.pdf', 'I');
    exit;
}












}
