<?php
require_once 'db.php';

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

function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

function requireLogin() {
    if (!isLoggedIn()) {
        redirect('login.php');
    }
}

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

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

function getDashboardStats() {
    global $db;
    
    $today = date('Y-m-d');
    $month = date('Y-m');
    
    $stats = [
        'today_invoices' => 0,
        'today_sales' => 0,
        'month_sales' => 0
    ];
    
    // عدد الفواتير اليوم
    $result = $db->fetchOne("SELECT COUNT(*) as count FROM invoices WHERE DATE(date) = ?", [$today]);
    $stats['today_invoices'] = $result['count'];
    
    // إجمالي المبيعات اليوم
    $result = $db->fetchOne("SELECT SUM(total_amount) as total FROM invoices WHERE DATE(date) = ?", [$today]);
    $stats['today_sales'] = $result['total'] ?? 0;
    
    // إجمالي المبيعات الشهرية
    $result = $db->fetchOne("SELECT SUM(total_amount) as total FROM invoices WHERE DATE_FORMAT(date, '%Y-%m') = ?", [$month]);
    $stats['month_sales'] = $result['total'] ?? 0;
    
    return $stats;
}

function getInvoices($limit = null) {
    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) {
        $sql .= " LIMIT " . intval($limit);
    }
    
    return $db->fetchAll($sql);
}

function getInvoice($invoiceId) {
    global $db;
    
    $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;
}

function searchInvoices($searchTerm) {
    global $db;
    
    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%"]);
}

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

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

function generateInvoiceNumber() {
    global $db;
    
    do {
        $randomNumber = str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
        
        // التحقق من عدم وجود الرقم مسبقًا
        $existingInvoice = $db->fetchOne("SELECT id FROM invoices WHERE invoice_number = ?", [$randomNumber]);
    } while ($existingInvoice);
    
    return $randomNumber;
}