<?php
class InvoiceController {
    public function create(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();

        $tid = Auth::tenantId();

        // Get locations
        $locStmt = db()->prepare("SELECT * FROM locations WHERE tenant_id=?");
        $locStmt->execute([$tid]);
        $locations = $locStmt->fetchAll();

        // Get customers
        $custStmt = db()->prepare("SELECT * FROM customers WHERE tenant_id=? AND is_active=1 ORDER BY name ASC");
        $custStmt->execute([$tid]);
        $customers = $custStmt->fetchAll();

        // Load payment methods settings
        $stmt = db()->prepare("SELECT * FROM settings WHERE tenant_id=?");
        $stmt->execute([$tid]);
        $settingsRaw = $stmt->fetchAll();
        $settings = [];
        foreach ($settingsRaw as $s) { $settings[$s['setting_key']] = $s['setting_value']; }
        
        // Get products with stock
        $prodStmt = db()->prepare("
            SELECT p.*, c.name as category_name,
                   COALESCE(SUM(s.quantity), 0) as total_stock
            FROM products p
            LEFT JOIN categories c ON c.id = p.category_id
            LEFT JOIN stock s ON s.product_id = p.id AND s.tenant_id = p.tenant_id
            WHERE p.tenant_id = ? AND p.is_active = 1
            GROUP BY p.id
            ORDER BY p.name ASC
        ");
        $prodStmt->execute([$tid]);
        $products = $prodStmt->fetchAll();
        
        // Get tax settings
        $taxRate = setting('tax_rate', 0);
        $taxEnabled = setting('tax_enabled', 0);
        
        $pageTitle = 'Create Sale Invoice';
        ob_start();
        include APP_ROOT . '/views/tenant/invoices/create.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/tenant/layouts/main.php';
    }
    
    public function store(): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        Security::checkCsrf();
        
        try {
            $tid = Auth::tenantId();
            
            $saleData = [
                'customer_id'     => !empty($_POST['customer_id']) ? (int)$_POST['customer_id'] : null,
                'subtotal'        => (float)$_POST['subtotal'],
                'discount_amount' => (float)($_POST['discount_amount'] ?? 0),
                'tax_amount'      => (float)($_POST['tax_amount'] ?? 0),
                'total'           => (float)$_POST['total'],
                'amount_paid'     => (float)($_POST['paid_amount'] ?? 0),
                'payment_method'  => Security::sanitize($_POST['payment_method'] ?? 'cash'),
                'payment_status'  => Security::sanitize($_POST['payment_status'] ?? 'due'),
                'status'          => 'completed',
                'note'            => Security::sanitize($_POST['notes'] ?? '')
            ];

            $locationId = (int)$_POST['location_id'];
            if (!$locationId) {
                throw new Exception("Location is required");
            }
            
            // Parse items from POST
            $items = [];
            if (isset($_POST['items']) && is_array($_POST['items'])) {
                foreach ($_POST['items']['product_id'] as $index => $productId) {
                    if (empty($productId)) continue;
                    
                    $items[] = [
                        'product_id' => (int)$productId,
                        'quantity'   => (float)$_POST['items']['quantity'][$index],
                        'unit_price' => (float)$_POST['items']['unit_price'][$index],
                        'discount'   => (float)($_POST['items']['discount'][$index] ?? 0),
                        'batch_id'   => !empty($_POST['items']['batch_id'][$index]) ? (int)$_POST['items']['batch_id'][$index] : null
                    ];
                }
            }
            
            if (empty($items)) {
                throw new Exception("At least one item is required");
            }
            
            $saleId = Sale::createWithItems($saleData, $items, $locationId);
            
            flash('success', 'Invoice created successfully');
            redirect('invoices/create');
            
        } catch (Exception $e) {
            flash('error', $e->getMessage());
            redirectBack();
        }
    }
    
    public function print(string $id, string $format = 'a4'): void {
        Auth::requireLogin();
        Auth::requireActiveTenant();
        
        $sale = Sale::withItems((int)$id);
        if (!$sale) { flash('error', 'Sale not found'); redirect('sales'); }
        
        $tid = Auth::tenantId();
        
        // Get tenant info
        $tenant = db()->prepare("SELECT * FROM tenants WHERE id=?");
        $tenant->execute([$tid]);
        $tenant = $tenant->fetch();
        
        // Get customer if exists
        $customer = null;
        if ($sale['customer_id']) {
            $custStmt = db()->prepare("SELECT * FROM customers WHERE id=? AND tenant_id=?");
            $custStmt->execute([$sale['customer_id'], $tid]);
            $customer = $custStmt->fetch();
        }
        
        // Get location
        $locStmt = db()->prepare("SELECT * FROM locations WHERE id=?");
        $locStmt->execute([$sale['location_id']]);
        $location = $locStmt->fetch();
        
        // Determine view based on format
        $view = match($format) {
            'pos80' => 'invoice-print-pos80.php',
            'pos50' => 'invoice-print-pos50.php',
            default => 'invoice-print-a4.php'
        };
        
        // Invoice print views are self-contained with their own print triggers
        include APP_ROOT . "/views/tenant/invoices/{$view}";
    }
}
