<?php
require_once 'db.php';

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

function isLoggedIn(): bool {
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

function requireLogin(): void {
    if (!isLoggedIn()) {
        $_SESSION['redirect_url'] = $_SERVER['REQUEST_URI'] ?? '';
        redirect('login.php');
    }
}

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

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

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

function getInvoices(int $limit = 0): 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;
    }
    
    return $db->fetchAll($sql) ?: [];
}

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("Error in getInvoice: " . $e->getMessage());
        return null;
    }
}

function searchInvoices(string $searchTerm): array {
    global $db;
    
    try {
        $searchTerm = trim($searchTerm);
        if (empty($searchTerm)) {
            return [];
        }
        
        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("Error in searchInvoices: " . $e->getMessage());
        return [];
    }
}

function getProducts(): array {
    global $db;
    return $db->fetchAll("SELECT * FROM products ORDER BY name") ?: [];
}

function getCustomers(): array {
    global $db;
    return $db->fetchAll("SELECT * FROM customers ORDER BY name") ?: [];
}

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