<?php
require_once 'db.php';

function redirect(string $url): never {
    header("Location: $url");
    exit();
}

function formatDate(string $date): string {
    return date('d/m/Y', strtotime($date) ?: time());
}

function formatCurrency(float $amount): string {
    return number_format($amount, 2) . ' ج.م';
}

function getDashboardStats(): array {
    global $db;
    
    $today = date('Y-m-d');
    $month = date('Y-m');
    
    try {
        $stats = [
            'today_invoices' => (int)$db->fetchOne("SELECT COUNT(*) as count FROM invoices WHERE DATE(date) = ?", [$today])['count'],
            'today_sales' => (float)($db->fetchOne("SELECT COALESCE(SUM(total_amount), 0) as total FROM invoices WHERE DATE(date) = ?", [$today])['total']),
            'month_sales' => (float)($db->fetchOne("SELECT COALESCE(SUM(total_amount), 0) as total FROM invoices WHERE DATE_FORMAT(date, '%Y-%m') = ?", [$month])['total'])
        ];
    } catch (Exception $e) {
        error_log("Dashboard stats error: " . $e->getMessage());
        $stats = [
            'today_invoices' => 0,
            'today_sales' => 0,
            'month_sales' => 0
        ];
    }
    
    return $stats;
}

function getInvoices(?int $limit = null): array {
    global $db;
    
    $sql = "SELECT i.*, c.name as customer_name 
            FROM invoices i
            LEFT JOIN customers c ON i.customer_id = c.id
            ORDER BY i.date DESC, i.id DESC";
    
    if ($limit > 0) {
        $sql .= " LIMIT " . $limit;
    }
    
    try {
        return $db->fetchAll($sql) ?: [];
    } catch (Exception $e) {
        error_log("Get invoices error: " . $e->getMessage());
        return [];
    }
}

function getInvoice(int $invoiceId): ?array {
    global $db;
    
    try {
        $invoice = $db->fetchOne(
            "SELECT i.*, c.name as customer_name, c.phone as customer_phone 
             FROM invoices i
             LEFT JOIN customers c ON i.customer_id = c.id
             WHERE i.id = ?", 
            [$invoiceId]
        );
        
        if ($invoice) {
            $invoice['items'] = $db->fetchAll(
                "SELECT * FROM invoice_items WHERE invoice_id = ?",
                [$invoiceId]
            ) ?: [];
        }
        
        return $invoice;
    } catch (Exception $e) {
        error_log("Get invoice error: " . $e->getMessage());
        return null;
    }
}

function searchInvoices(string $searchTerm): array {
    global $db;
    
    try {
        $searchTerm = '%' . str_replace(['%', '_'], ['\%', '\_'], $searchTerm) . '%';
        
        return $db->fetchAll(
            "SELECT i.*, c.name as customer_name 
             FROM invoices i
             LEFT JOIN customers c ON i.customer_id = c.id
             WHERE i.invoice_number LIKE ? OR c.name LIKE ?
             ORDER BY i.date DESC",
            [$searchTerm, $searchTerm]
        ) ?: [];
    } catch (Exception $e) {
        error_log("Search invoices error: " . $e->getMessage());
        return [];
    }
}

function getProducts(): array {
    global $db;
    try {
        return $db->fetchAll("SELECT * FROM products ORDER BY name") ?: [];
    } catch (Exception $e) {
        error_log("Get products error: " . $e->getMessage());
        return [];
    }
}

function getCustomers(): array {
    global $db;
    try {
        return $db->fetchAll("SELECT * FROM customers ORDER BY name") ?: [];
    } catch (Exception $e) {
        error_log("Get customers error: " . $e->getMessage());
        return [];
    }
}

function generateInvoiceNumber(): string {
    global $db;
    
    try {
        do {
            $randomNumber = str_pad(random_int(1, 999999), 6, '0', STR_PAD_LEFT);
            $exists = $db->fetchOne(
                "SELECT 1 FROM invoices WHERE invoice_number = ? LIMIT 1",
                [$randomNumber]
            );
        } while ($exists);
        
        return $randomNumber;
    } catch (Exception $e) {
        error_log("Generate invoice number error: " . $e->getMessage());
        return str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
    }
}