<?php
// Error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Set timezone
date_default_timezone_set('Africa/Casablanca');

// Database connection
function getDB() {
    static $db = null;
    if ($db === null) {
        try {
            $db = new SQLite3(__DIR__ . '/../database/app.db');
            $db->enableExceptions(true);
            $db->exec('PRAGMA foreign_keys = ON;');
        } catch (Exception $e) {
            error_log('Database connection error: ' . $e->getMessage());
            die('خطأ في الاتصال بقاعدة البيانات');
        }
    }
    return $db;
}

// Load required files
require_once __DIR__ . '/auth.php';

// Helper functions
function formatMoney($amount) {
    return number_format($amount, 2, '.', ',') . ' درهم';
}

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

function validateDate($date) {
    $d = DateTime::createFromFormat('Y-m-d', $date);
    return $d && $d->format('Y-m-d') === $date;
}

function validateAmount($amount) {
    return is_numeric($amount) && $amount >= 0;
}

// CSRF protection
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die('CSRF token validation failed');
    }
}

// Set character encoding
header('Content-Type: text/html; charset=utf-8');
