<?php
// includes/config.php
session_start();

// ========================
// 🔧 اطلاعات دیتابیس تو
// ========================

$db_host = 'localhost';                 // همین بماند
$db_name = 'unfupklo_benzin';           // نام دیتابیس تو
$db_user = 'unfupklo_benzin';           // کاربر دیتابیس تو  
$db_pass = 'G)lZ=H6fTpJk';              // رمز دیتابیس تو

// ========================
// 🎯 تنظیمات سایت
// ========================

define('SITE_NAME', 'سامانه مدیریت سوخت');
define('SITE_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/');

// تنظیم زمان تهران
date_default_timezone_set('Asia/Tehran');

// ========================
// 📅 توابع تاریخ شمسی (کاربردی)
// ========================

/**
 * تبدیل تاریخ میلادی به شمسی
 */
function gregorian_to_jalali($g_y, $g_m, $g_d)
{
    $g_days_in_month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    $j_days_in_month = array(31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29);
    
    $gy = $g_y-1600;
    $gm = $g_m-1;
    $gd = $g_d-1;
    
    $g_day_no = 365*$gy + floor(($gy+3)/4) - floor(($gy+99)/100) + floor(($gy+399)/400);
    
    for ($i=0; $i < $gm; ++$i)
        $g_day_no += $g_days_in_month[$i];
    if ($gm>1 && (($gy%4==0 && $gy%100!=0) || ($gy%400==0)))
        $g_day_no++;
    $g_day_no += $gd;
    
    $j_day_no = $g_day_no-79;
    
    $j_np = floor($j_day_no/ 12053);
    $j_day_no = $j_day_no % 12053;
    
    $jy = 979+33*$j_np+4*floor($j_day_no/1461);
    $j_day_no %= 1461;
    
    if ($j_day_no >= 366) {
        $jy += floor(($j_day_no-1)/365);
        $j_day_no = ($j_day_no-1)%365;
    }
    
    for ($i = 0; $i < 11 && $j_day_no >= $j_days_in_month[$i]; ++$i)
        $j_day_no -= $j_days_in_month[$i];
    $jm = $i+1;
    $jd = $j_day_no+1;
    
    return array($jy, $jm, $jd);
}

/**
 * نمایش تاریخ شمسی
 */
function persianDate($date, $format = 'Y/m/d')
{
    if (empty($date) || $date == '0000-00-00') {
        return '-';
    }
    
    // فقط تاریخ را بگیر (اگر زمان هم دارد)
    $date = substr($date, 0, 10);
    
    // جدا کردن سال، ماه، روز
    list($g_y, $g_m, $g_d) = explode('-', $date);
    
    // تبدیل به شمسی
    list($j_y, $j_m, $j_d) = gregorian_to_jalali($g_y, $g_m, $g_d);
    
    // نام ماه‌های شمسی
    $j_month_names = array(
        '', 'فروردین', 'اردیبهشت', 'خرداد', 
        'تیر', 'مرداد', 'شهریور',
        'مهر', 'آبان', 'آذر', 
        'دی', 'بهمن', 'اسفند'
    );
    
    // نام روزهای هفته
    $j_day_names = array(
        'یکشنبه', 'دوشنبه', 'سه‌شنبه', 'چهارشنبه',
        'پنجشنبه', 'جمعه', 'شنبه'
    );
    
    // ایجاد timestamp برای روز هفته
    $timestamp = strtotime($date);
    $day_of_week = date('w', $timestamp); // 0=یکشنبه
    
    // فرمت‌دهی
    $result = $format;
    
    // سال
    $result = str_replace('Y', $j_y, $result);
    $result = str_replace('y', substr($j_y, -2), $result);
    
    // ماه
    $result = str_replace('m', ($j_m < 10 ? '0' : '') . $j_m, $result);
    $result = str_replace('n', $j_m, $result);
    $result = str_replace('F', $j_month_names[$j_m], $result);
    $result = str_replace('M', $j_month_names[$j_m], $result);
    
    // روز
    $result = str_replace('d', ($j_d < 10 ? '0' : '') . $j_d, $result);
    $result = str_replace('j', $j_d, $result);
    
    // روز هفته
    $result = str_replace('l', $j_day_names[$day_of_week], $result);
    $result = str_replace('D', mb_substr($j_day_names[$day_of_week], 0, 2, 'UTF-8'), $result);
    
    return $result;
}

/**
 * تاریخ امروز به شمسی
 */
function todayPersian($format = 'l d F Y')
{
    $today = date('Y-m-d');
    return persianDate($today, $format);
}

/**
 * فرمت کردن اعداد به فارسی
 */
function formatNumber($number, $decimals = 0)
{
    if (!is_numeric($number)) {
        return $number;
    }
    
    // فرمت عدد
    $formatted = number_format($number, $decimals);
    
    // تبدیل ارقام انگلیسی به فارسی
    $persian_digits = array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹');
    $english_digits = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
    
    return str_replace($english_digits, $persian_digits, $formatted);
}

/**
 * فرمت قیمت
 */
function formatPrice($price)
{
    return formatNumber($price) . ' تومان';
}

/**
 * فرمت مقدار سوخت
 */
function formatFuel($amount)
{
    return formatNumber($amount, 1) . ' لیتر';
}

// ========================
// 🗄️ اتصال به دیتابیس
// ========================

function getDB()
{
    global $db_host, $db_name, $db_user, $db_pass;
    
    static $db = null;
    
    if ($db === null) {
        try {
            $dsn = "mysql:host=$db_host;dbname=$db_name;charset=utf8mb4";
            $db = new PDO($dsn, $db_user, $db_pass);
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
            $db->exec("SET NAMES utf8mb4");
            
        } catch(PDOException $e) {
            die("<div style='text-align:center; padding:50px; font-family:Tahoma;'>
                    <h2 style='color:red;'>❌ خطا در اتصال به دیتابیس</h2>
                    <p>لطفاً با مدیر سیستم تماس بگیرید.</p>
                 </div>");
        }
    }
    
    return $db;
}

// ========================
// 🔐 احراز هویت
// ========================

function isLoggedIn()
{
    return isset($_SESSION['user_id']);
}

function isAdmin()
{
    return isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
}

function requireLogin()
{
    if (!isLoggedIn()) {
        $_SESSION['error'] = "لطفاً ابتدا وارد شوید";
        header('Location: ' . SITE_URL . 'login.php');
        exit();
    }
}

function requireAdmin()
{
    requireLogin();
    if (!isAdmin()) {
        $_SESSION['error'] = "شما دسترسی لازم را ندارید";
        header('Location: ' . SITE_URL . 'index.php');
        exit();
    }
}

function redirect($url)
{
    header("Location: " . $url);
    exit();
}

// ========================
// 🛡️ امنیت
// ========================

function safe($text)
{
    if (is_array($text)) {
        return array_map('safe', $text);
    }
    return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}

// ========================
// ✅ بررسی نصب
// ========================

function isInstalled()
{
    try {
        $db = getDB();
        $result = $db->query("SHOW TABLES LIKE 'users'");
        return $result->rowCount() > 0;
    } catch(Exception $e) {
        return false;
    }
}

// ========================
// 💬 نمایش پیام
// ========================

function showMessages()
{
    if (isset($_SESSION['success'])) {
        echo '<div class="alert alert-success alert-dismissible fade show">
                <i class="bi bi-check-circle"></i> ' . safe($_SESSION['success']) . '
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
              </div>';
        unset($_SESSION['success']);
    }
    
    if (isset($_SESSION['error'])) {
        echo '<div class="alert alert-danger alert-dismissible fade show">
                <i class="bi bi-x-circle"></i> ' . safe($_SESSION['error']) . '
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
              </div>';
        unset($_SESSION['error']);
    }
    
    if (isset($_SESSION['info'])) {
        echo '<div class="alert alert-info alert-dismissible fade show">
                <i class="bi bi-info-circle"></i> ' . safe($_SESSION['info']) . '
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
              </div>';
        unset($_SESSION['info']);
    }
}

// ========================
// 📊 توابع کمکی
// ========================

function getStats()
{
    $db = getDB();
    $stats = [];
    
    // خودروها
    $stmt = $db->query("SELECT COUNT(*) as count FROM vehicles");
    $stats['vehicles'] = $stmt->fetch()['count'];
    
    // سوخت امروز
    $today = date('Y-m-d');
    $stmt = $db->prepare("SELECT COUNT(*) as count, SUM(fuel_amount) as total_fuel FROM fuel_records WHERE fuel_date = ?");
    $stmt->execute([$today]);
    $today_stats = $stmt->fetch();
    $stats['today_records'] = $today_stats['count'];
    $stats['today_fuel'] = $today_stats['total_fuel'] ?? 0;
    
    // کاربران
    $stmt = $db->query("SELECT COUNT(*) as count FROM users");
    $stats['users'] = $stmt->fetch()['count'];
    
    return $stats;
}

function getVehicles()
{
    $db = getDB();
    $stmt = $db->query("SELECT * FROM vehicles ORDER BY license_plate");
    return $stmt->fetchAll();
}

function getRecentFuel($limit = 5)
{
    $db = getDB();
    $stmt = $db->prepare("
        SELECT fr.*, v.license_plate, v.model 
        FROM fuel_records fr
        JOIN vehicles v ON fr.vehicle_id = v.id
        ORDER BY fr.created_at DESC 
        LIMIT ?
    ");
    $stmt->execute([$limit]);
    return $stmt->fetchAll();
}

// ========================
// 🎨 منو
// ========================

function getMenuItems()
{
    $items = [
        ['icon' => 'bi-speedometer2', 'text' => 'داشبورد', 'link' => 'index.php'],
        ['icon' => 'bi-truck', 'text' => 'خودروها', 'link' => 'vehicles.php'],
        ['icon' => 'bi-droplet-fill', 'text' => 'ثبت سوخت', 'link' => 'add_fuel.php'],
        ['icon' => 'bi-graph-up', 'text' => 'گزارش‌ها', 'link' => 'reports.php'],
        ['icon' => 'bi-person-circle', 'text' => 'پروفایل', 'link' => 'profile.php'],
    ];
    
    if (isAdmin()) {
        $items[] = ['icon' => 'bi-people-fill', 'text' => 'کاربران', 'link' => 'users.php'];
    }
    
    $items[] = ['icon' => 'bi-box-arrow-right', 'text' => 'خروج', 'link' => 'logout.php'];
    
    return $items;
}

function isActive($page)
{
    $current = basename($_SERVER['PHP_SELF']);
    return ($current == $page) ? 'active' : '';
}

// ========================
// 🖨️ توابع نمایش
// ========================

function displayDate($date)
{
    return persianDate($date, 'Y/m/d');
}

function displayDateTime($datetime)
{
    $date = substr($datetime, 0, 10);
    $time = substr($datetime, 11, 5);
    return persianDate($date, 'Y/m/d') . ' ' . $time;
}

function displayPrice($price)
{
    return formatPrice($price);
}

function displayFuel($amount)
{
    return formatFuel($amount);
}

// ========================
// 📝 اعتبارسنجی فرم
// ========================

function validateRequired($fields)
{
    foreach ($fields as $field => $label) {
        if (empty(trim($_POST[$field] ?? ''))) {
            $_SESSION['error'] = "فیلد {$label} الزامی است";
            return false;
        }
    }
    return true;
}

function validateNumber($field, $label, $min = 0)
{
    $value = $_POST[$field] ?? '';
    if (!is_numeric($value) || $value < $min) {
        $_SESSION['error'] = "{$label} باید عددی و بزرگتر از {$min} باشد";
        return false;
    }
    return true;
}

// ========================
// 🎯 هدر و فوتر
// ========================

function getHeader()
{
    return '
    <!DOCTYPE html>
    <html lang="fa" dir="rtl">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>' . SITE_NAME . '</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
        <style>
            body { 
                background-color: #f8f9fa; 
                font-family: "Vazirmatn", Tahoma, sans-serif;
            }
            .sidebar {
                background: linear-gradient(180deg, #667eea 0%, #764ba2 100%);
                color: white;
                min-height: 100vh;
            }
            .stat-card {
                background: white;
                border-radius: 15px;
                padding: 20px;
                box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            }
        </style>
    </head>
    <body>
    ';
}

function getFooter()
{
    return '
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <script>
            // نمایش اعداد فارسی
            document.addEventListener("DOMContentLoaded", function() {
                var persianDigits = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"];
                var elements = document.querySelectorAll(".persian-number");
                elements.forEach(function(element) {
                    var text = element.textContent;
                    text = text.replace(/\d/g, function(digit) {
                        return persianDigits[digit];
                    });
                    element.textContent = text;
                });
            });
        </script>
    </body>
    </html>
    ';
}

?>