<?php
session_start();
require_once 'db_connect.php'; // تأكد من أن هذا الملف يحتوي على الاتصال بقاعدة البيانات

// التحقق من حالة التفعيل والفترة التجريبية
$user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
$activation_data = ['status' => 'not_activated', 'trial_start' => null];
$trial_days = 3; // الفترة التجريبية: 3 أيام
$trial_expired = false;
$remaining_time = null;
$error_message = null;

if ($user_id) {
    try {
        // التحقق مما إذا كان هناك سجل تفعيل للمستخدم الحالي في جدول activation
        $stmt = $conn->prepare("SELECT status, created_at FROM activation WHERE user_id = :user_id LIMIT 1");
        $stmt->execute([':user_id' => $user_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$result) {
            // إذا لم يكن هناك سجل، قم بإنشاء واحد مع تاريخ بدء الفترة التجريبية
            $trial_start = date('Y-m-d H:i:s');
            $stmt = $conn->prepare("INSERT INTO activation (user_id, hdd_serial, activation_code, status, created_at) VALUES (:user_id, '', '', 'not_activated', :created_at)");
            $stmt->execute([
                ':user_id' => $user_id,
                ':created_at' => $trial_start
            ]);
            $activation_data['trial_start'] = $trial_start;
            $activation_data['status'] = 'not_activated';
        } else {
            // إذا كان هناك سجل، قم بجلب البيانات
            $activation_data['status'] = $result['status'];
            $activation_data['trial_start'] = $result['created_at'];
        }

        // التحقق من حالة التفعيل
        if ($activation_data['status'] === 'not_activated') {
            $trial_start = new DateTime($activation_data['trial_start']);
            $now = new DateTime();
            $interval = $now->diff($trial_start);
            $days_passed = $interval->days;

            // حساب الوقت المتبقي
            $trial_end = (clone $trial_start)->modify("+{$trial_days} days");
            if ($now > $trial_end) {
                $trial_expired = true;
            } else {
                $remaining_interval = $now->diff($trial_end);
                $remaining_time = [
                    'days' => $remaining_interval->days,
                    'hours' => $remaining_interval->h,
                    'minutes' => $remaining_interval->i,
                    'seconds' => $remaining_interval->s
                ];
            }

            // إذا انتهت الفترة التجريبية ولم يتم التفعيل، أعد التوجيه إلى صفحة التفعيل
            if ($trial_expired && basename($_SERVER['PHP_SELF']) !== 'activation.php') {
                header("Location: activation.php");
                exit();
            }
        } else {
            // إذا كانت الحالة activated، تأكد من أن العداد لن يظهر
            $trial_expired = true;
            $remaining_time = null;
        }
    } catch (PDOException $e) {
        error_log("Error checking activation status: " . $e->getMessage());
        try {
            // إنشاء الجدول إذا لم يكن موجودًا
            $conn->exec("CREATE TABLE IF NOT EXISTS activation (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NOT NULL,
                hdd_serial VARCHAR(50) NOT NULL,
                activation_code VARCHAR(20) NOT NULL,
                status ENUM('activated', 'not_activated') DEFAULT 'not_activated',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                activated_at TIMESTAMP NULL
            )");

            // إعادة المحاولة بعد إنشاء الجدول
            $stmt = $conn->prepare("SELECT status, created_at FROM activation WHERE user_id = :user_id LIMIT 1");
            $stmt->execute([':user_id' => $user_id]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$result) {
                $trial_start = date('Y-m-d H:i:s');
                $stmt = $conn->prepare("INSERT INTO activation (user_id, hdd_serial, activation_code, status, created_at) VALUES (:user_id, '', '', 'not_activated', :created_at)");
                $stmt->execute([
                    ':user_id' => $user_id,
                    ':created_at' => $trial_start
                ]);
                $activation_data['trial_start'] = $trial_start;
                $activation_data['status'] = 'not_activated';
            } else {
                $activation_data['status'] = $result['status'];
                $activation_data['trial_start'] = $result['created_at'];
            }

            if ($activation_data['status'] === 'not_activated') {
                $trial_start = new DateTime($activation_data['trial_start']);
                $now = new DateTime();
                $trial_end = (clone $trial_start)->modify("+{$trial_days} days");
                if ($now > $trial_end) {
                    $trial_expired = true;
                } else {
                    $remaining_interval = $now->diff($trial_end);
                    $remaining_time = [
                        'days' => $remaining_interval->days,
                        'hours' => $remaining_interval->h,
                        'minutes' => $remaining_interval->i,
                        'seconds' => $remaining_interval->s
                    ];
                }

                if ($trial_expired && basename($_SERVER['PHP_SELF']) !== 'activation.php') {
                    header("Location: activation.php");
                    exit();
                }
            } else {
                $trial_expired = true;
                $remaining_time = null;
            }
        } catch (PDOException $e) {
            // إذا استمر الخطأ، قم بتسجيله وتعيين قيم افتراضية
            error_log("Repeated error checking activation status: " . $e->getMessage());
            $error_message = "حدث خطأ أثناء التحقق من حالة التفعيل: " . htmlspecialchars($e->getMessage());
            $trial_expired = true;
            $remaining_time = null;
        }
    }
}

require_once 'check_permissions.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

// جلب اسم المستخدم من الجلسة
$user_name = isset($_SESSION['username']) ? $_SESSION['username'] : 'غير معروف';

// التحقق من صلاحية الوصول إلى الصفحة الحالية
$screen = basename($_SERVER['PHP_SELF'], '.php');
checkPermission($conn, $screen);

// جلب الأصناف منخفضة المخزون
$low_stock_items = [];
try {
$stmt = $conn->prepare("SELECT name FROM items WHERE quantity <= min_quantity");
    $stmt->execute();
    $low_stock_items = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching low stock items: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Astra - لوحة التحكم</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            min-height: 100vh; /* تغيير height إلى min-height للسماح بالتمرير */
            direction: rtl;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #4169E1;
            transition: background 0.5s ease;
            overflow-x: hidden; /* منع التمرير الأفقي */
        }

        .background {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(135deg, #4169E1, #87CEEB, #2747B9);
            z-index: -1;
            animation: gradientFlow 15s ease infinite;
            transition: background 0.5s ease;
        }

        @keyframes gradientFlow {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }

        .particles {
            position: absolute;
            width: 100%;
            height: 100%;
            z-index: 0;
        }

        .dashboard-container {
            position: relative;
            z-index: 1;
            min-height: 100vh; /* ضمان أن المحتوى يأخذ الارتفاع الكامل */
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .header {
            text-align: center;
            padding: 20px 0;
            z-index: 10;
        }

        .header .logo {
            width: 50px;
            height: 50px;
            vertical-align: middle;
            margin-left: 10px;
        }

        .header h1 {
            color: #fff;
            font-size: 2.5rem;
            font-weight: bold;
            text-shadow: 0 0 10px rgba(255, 255, 255, 0.7);
            display: inline;
            animation: glow 2s ease-in-out infinite alternate;
        }

        .top-nav {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            padding: 15px 30px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
            position: relative;
            z-index: 10;
        }

        .navbar-nav {
            margin-right: 0;
            padding-right: 0;
            width: 100%; /* جعل القائمة تأخذ العرض الكامل */
            justify-content: space-around; /* توزيع العناصر */
        }

        .navbar-nav .nav-item {
            margin-left: 10px;
        }

        .navbar-nav .nav-link {
            color: #fff;
            font-size: 1rem;
            padding: 10px 15px;
            border-radius: 10px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            white-space: nowrap;
        }

        .navbar-nav .nav-link:hover {
            opacity: 0.9;
            transform: translateY(-2px);
        }

        .navbar-nav .nav-link i {
            margin-left: 8px;
        }

        .dropdown-menu {
            background: rgba(255, 255, 255, 0.95);
            border: none;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            right: 0;
            z-index: 11;
            min-width: 250px;
        }

        .dropdown-menu a {
            color: #fff;
            padding: 8px 15px;
            text-align: right;
            display: flex;
            align-items: center;
            font-size: 0.9rem;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .dropdown-menu a i {
            margin-left: 8px;
        }

        .dropdown-menu a:hover {
            opacity: 0.9;
        }

        @keyframes glow {
            from { text-shadow: 0 0 5px #fff, 0 0 10px #4169E1; }
            to { text-shadow: 0 0 10px #fff, 0 0 20px #4169E1; }
        }

        .nav-suppliers { background: #1ABC9C; transition: background 0.3s ease; }
        .nav-clients { background: #E74C3C; transition: background 0.3s ease; }
        .nav-employees { background: #9B59B6; transition: background 0.3s ease; }
        .nav-items { background: #FF5733; transition: background 0.3s ease; }
        .nav-sales { background: #2ECC71; transition: background 0.3s ease; }
        .nav-purchases { background: #F1C40F; transition: background 0.3s ease; }
        .nav-treasury { background: #3498DB; transition: background 0.3s ease; }
        .nav-stores { background: #E67E22; transition: background 0.3s ease; }
        .nav-settings { background: #D35400; transition: background 0.3s ease; }

        .dropdown-item-suppliers { background: #16A085; }
        .dropdown-item-supplier-statement { background: #1ABC9C; }
        .dropdown-item-supplier-report { background: #48C9B0; }
        .dropdown-item-clients { background: #C0392B; }
        .dropdown-item-client-statement { background: #E74C3C; }
        .dropdown-item-client-report { background: #EC7063; }
        .dropdown-item-monthly-payments { background: #F1948A; }
        .dropdown-item-employee-management { background: #8E44AD; }
        .dropdown-item-salary-payments { background: #9B59B6; }
        .dropdown-item-employee-report { background: #BB8FCE; }
        .dropdown-item-items { background: #E74C3C; }
        .dropdown-item-categories { background: #FF5733; }
        .dropdown-item-units { background: #FF7043; }
        .dropdown-item-barcode { background: #F1948A; }
        .dropdown-item-item-movement { background: #EC7063; }
        .dropdown-item-sales-invoice { background: #27AE60; }
        .dropdown-item-sales-invoices { background: #2ECC71; }
        .dropdown-item-pending-invoices { background: #52BE80; }
        .dropdown-item-sales-return { background: #76D7C4; }
        .dropdown-item-sales-return-invoices { background: #A9DFBF; }
        .dropdown-item-purchase-invoice { background: #F4D03F; }
        .dropdown-item-purchase-invoices { background: #F1C40F; }
        .dropdown-item-purchase-return { background: #F7DC6F; }
        .dropdown-item-purchase-return-invoices { background: #F9E79F; }
        .dropdown-item-treasury { background: #2874A6; }
        .dropdown-item-treasury-manage { background: #3498DB; }
        .dropdown-item-treasury-transfer { background: #5DADE2; }
        .dropdown-item-daily-revenue { background: #85C1E9; }
        .dropdown-item-deposit { background: #AED6F1; }
        .dropdown-item-withdraw { background: #D6EAF8; }
        .dropdown-item-expenses { background: #EBF5FB; }
        .dropdown-item-expense-types { background: #D5F5E3; }
        .dropdown-item-store-add { background: #D35400; }
        .dropdown-item-store-transfer { background: #E67E22; }
        .dropdown-item-store-inventory { background: #F39C12; }
        .dropdown-item-settings { background: #BA4A00; }
        .dropdown-item-users { background: #D35400; }
        .dropdown-item-backup { background: #E67E22; }
        .dropdown-item-activation { background: #F39C12; }

        .sidebar {
            position: fixed;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 200px;
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(10px);
            border-radius: 0 15px 15px 0;
            padding: 20px;
            text-align: center;
            z-index: 10;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            animation: slideIn 0.5s ease-in-out;
        }

        .sidebar i {
            font-size: 2rem;
            color: #fff;
            margin-bottom: 10px;
            animation: bounce 2s infinite;
        }

        .sidebar .welcome {
            color: #fff;
            font-size: 1.2rem;
            font-weight: bold;
            text-shadow: 0 0 5px rgba(255, 255, 255, 0.7);
        }

        .sidebar .username {
            color: #4169E1;
            font-size: 1.5rem;
            font-weight: bold;
            background: rgba(255, 255, 255, 0.9);
            padding: 5px 15px;
            border-radius: 10px;
            display: inline-block;
            margin-top: 10px;
            transition: color 0.3s ease;
        }

        .sidebar .toggle-theme {
            margin-top: 20px;
            background: #4169E1;
            color: #fff;
            border: none;
            padding: 10px 20px;
            border-radius: 10px;
            cursor: pointer;
            transition: background 0.3s ease;
        }

        .sidebar .toggle-theme:hover {
            background: #2747B9;
        }

        @keyframes slideIn {
            from { left: -200px; }
            to { left: 0; }
        }

        @keyframes bounce {
            0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
            40% { transform: translateY(-10px); }
            60% { transform: translateY(-5px); }
        }

        .welcome-sidebar {
            position: fixed;
            right: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 250px;
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(10px);
            border-radius: 15px 0 0 15px;
            padding: 20px;
            text-align: center;
            z-index: 10;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            animation: slideInRight 0.5s ease-in-out;
        }

        .welcome-sidebar i {
            font-size: 2rem;
            color: #fff;
            margin-bottom: 10px;
            animation: bounce 2s infinite;
        }

        .welcome-sidebar .welcome-text {
            color: #2ECC71;
            font-size: 1.2rem;
            font-weight: bold;
            background: rgba(255, 255, 255, 0.9);
            padding: 5px 15px;
            border-radius: 10px;
            display: inline-block;
            transition: color 0.3s ease;
            animation: rotateTextLight 5s linear infinite;
        }

        .welcome-sidebar .daily-phrase {
            color: #fff;
            font-size: 1rem;
            margin-top: 10px;
            text-shadow: 0 0 5px rgba(255, 255, 255, 0.7);
        }

        @keyframes slideInRight {
            from { right: -250px; }
            to { right: 0; }
        }

        @keyframes rotateTextLight {
            0% { transform: rotate(0deg); }
            25% { transform: rotate(5deg); }
            75% { transform: rotate(-5deg); }
            100% { transform: rotate(0deg); }
        }

       .ticker {
    position: fixed;
    bottom: 60px;
    width: 100%;
    background: rgba(255, 0, 0, 0.8);
    color: #fff;
    padding: 10px 0;
    z-index: 10;
    overflow: hidden;
    white-space: nowrap;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.2);
    transition: background 0.3s ease;
}

.ticker-content {
    display: inline-block;
    padding-right: 20px;
    animation: marquee 500s linear infinite;
}

.ticker-content:hover {
    animation-play-state: paused;
}

.ticker-content span {
    margin: 0 20px;
    font-weight: bold;
}

@keyframes marquee {
    0% { transform: translateX(100%); }
    100% { transform: translateX(-100%); }
}
        .shortcuts {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            gap: 20px;
            padding: 20px 250px 70px 200px;
            flex-grow: 1;
            z-index: 5;
        }

        .shortcut-row {
            display: flex;
            justify-content: center;
            gap: 20px;
            width: 100%;
            max-width: 1200px;
            flex-wrap: wrap; /* السماح للبطاقات بالالتفاف على الشاشات الصغيرة */
        }

        .shortcut-card {
            width: 150px;
            height: 150px;
            border-radius: 15px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            text-align: center;
            transition: all 0.4s ease;
            cursor: pointer;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            position: relative;
            overflow: hidden;
        }

        .shortcut-card:hover {
            transform: translateY(-10px) rotate(2deg);
            box-shadow: 0 15px 30px rgba(0, 0, 0, 0.3);
        }

        .shortcut-card i {
            font-size: 2rem;
            color: #fff;
            margin-bottom: 10px;
        }

        .shortcut-card h3 {
            color: #fff;
            font-size: 1rem;
            margin: 0;
        }

        .card-items { background: #FF5733; transition: background 0.3s ease; }
        .card-sales-invoice { background: #4169E1; transition: background 0.3s ease; }
        .card-purchase-invoice { background: #2ECC71; transition: background 0.3s ease; }
        .card-item-search { background: #F1C40F; transition: background 0.3s ease; }
        .card-inventory { background: #E67E22; transition: background 0.3s ease; }
        .card-treasury { background: #9B59B6; transition: background 0.3s ease; }
        .card-stores { background: #3498DB; transition: background 0.3s ease; }
        .card-clients { background: #E74C3C; transition: background 0.3s ease; }
        .card-suppliers { background: #1ABC9C; transition: background 0.3s ease; }
        .card-logout { background: #7F8C8D; transition: background 0.3s ease; }
        .card-shift-close { background: #D35400; transition: background 0.3s ease; }
        .card-contact { background: #00CED1; transition: background 0.3s ease; }

        .footer {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            padding: 10px;
            text-align: center;
            color: #fff;
            font-size: 1rem;
            border-top: 1px solid rgba(255, 255, 255, 0.2);
            z-index: 5;
            transition: background 0.3s ease;
        }

        .dark-theme body {
            background: #2C3E50;
        }

        .dark-theme .background {
            background: linear-gradient(135deg, #2C3E50, #34495E, #1B263B);
        }

        .dark-theme .sidebar .username,
        .dark-theme .welcome-sidebar .welcome-text {
            color: #E74C3C;
        }

        .dark-theme .ticker {
            background: rgba(231, 76, 60, 0.8);
        }

        .dark-theme .card-items { background: #E74C3C; }
        .dark-theme .card-sales-invoice { background: #3498DB; }
        .dark-theme .card-purchase-invoice { background: #F1C40F; }
        .dark-theme .card-item-search { background: #2ECC71; }
        .dark-theme .card-inventory { background: #D35400; }
        .dark-theme .card-treasury { background: #9B59B6; }
        .dark-theme .card-stores { background: #E67E22; }
        .dark-theme .card-clients { background: #1ABC9C; }
        .dark-theme .card-suppliers { background: #FF5733; }
        .dark-theme .card-logout { background: #95A5A6; }
        .dark-theme .card-shift-close { background: #8E44AD; }
        .dark-theme .card-contact { background: #16A085; }

        .dark-theme .nav-suppliers { background: #16A085; }
        .dark-theme .nav-clients { background: #C0392B; }
        .dark-theme .nav-employees { background: #8E44AD; }
        .dark-theme .nav-items { background: #E74C3C; }
        .dark-theme .nav-sales { background: #27AE60; }
        .dark-theme .nav-purchases { background: #F4D03F; }
        .dark-theme .nav-treasury { background: #2874A6; }
        .dark-theme .nav-stores { background: #D35400; }
        .dark-theme .nav-settings { background: #BA4A00; }

        /* إضافة أسلوب لـ Modal */
        .modal-content {
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
        }
        .modal-header {
            background: #E74C3C;
            color: #fff;
            border-radius: 15px 15px 0 0;
        }
        .modal-body {
            text-align: center;
            font-size: 1.1rem;
            color: #333;
        }

        /* تنسيق العداد التنازلي أعلى الشعار */
        .trial-counter {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            z-index: 20;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
            background: rgba(231, 76, 60, 0.8);
            color: #fff;
            padding: 10px;
            text-align: center;
        }

        /* Media Queries للتوافق مع الشاشات المختلفة */
        @media (max-width: 992px) {
            .navbar-nav {
                flex-direction: column; /* جعل القائمة عمودية على الشاشات المتوسطة */
                align-items: flex-end;
            }

            .navbar-nav .nav-item {
                margin-left: 0;
                margin-bottom: 10px;
            }

            .navbar-nav .nav-link {
                font-size: 0.9rem;
                padding: 8px 12px;
            }

            .dropdown-menu {
                min-width: 200px;
                right: auto;
                left: 0;
            }

            .shortcuts {
                padding: 20px 10px 70px 10px; /* تقليل الهوامش على الشاشات المتوسطة */
            }

            .shortcut-card {
                width: 120px;
                height: 120px;
            }

            .shortcut-card i {
                font-size: 1.5rem;
            }

            .shortcut-card h3 {
                font-size: 0.9rem;
            }

            .sidebar, .welcome-sidebar {
                display: none; /* إخفاء الشريط الجانبي على الشاشات المتوسطة */
            }
        }

        @media (max-width: 768px) {
            .header h1 {
                font-size: 2rem;
            }

            .header .logo {
                width: 40px;
                height: 40px;
            }

            .top-nav {
                padding: 10px 15px;
            }

            .navbar-nav .nav-link {
                font-size: 0.8rem;
                padding: 6px 10px;
            }

            .dropdown-menu a {
                font-size: 0.8rem;
                padding: 6px 12px;
            }

            .shortcuts {
                padding: 20px 10px 70px 10px;
            }

            .shortcut-row {
                gap: 15px;
            }

            .shortcut-card {
                width: 100px;
                height: 100px;
            }

            .shortcut-card i {
                font-size: 1.2rem;
            }

            .shortcut-card h3 {
                font-size: 0.8rem;
            }

            .ticker {
                bottom: 50px;
                padding: 8px 0;
            }

            .ticker-content span {
                margin: 0 15px;
                font-size: 0.9rem;
            }

            .footer {
                font-size: 0.9rem;
                padding: 8px;
            }

            .trial-counter h4 {
                font-size: 1.2rem;
            }

            .trial-counter #trial-countdown {
                font-size: 1.2rem;
            }

            .trial-counter p {
                font-size: 0.9rem;
            }
        }

        @media (max-width: 576px) {
            .header h1 {
                font-size: 1.5rem;
            }

            .header .logo {
                width: 30px;
                height: 30px;
            }

            .navbar-nav .nav-link {
                font-size: 0.7rem;
                padding: 5px 8px;
            }

            .dropdown-menu {
                min-width: 180px;
            }

            .dropdown-menu a {
                font-size: 0.7rem;
                padding: 5px 10px;
            }

            .shortcuts {
                padding: 20px 5px 60px 5px;
            }

            .shortcut-row {
                gap: 10px;
            }

            .shortcut-card {
                width: 80px;
                height: 80px;
            }

            .shortcut-card i {
                font-size: 1rem;
            }

            .shortcut-card h3 {
                font-size: 0.7rem;
            }

            .ticker {
                bottom: 40px;
                padding: 6px 0;
            }

            .ticker-content span {
                margin: 0 10px;
                font-size: 0.8rem;
            }

            .footer {
                font-size: 0.8rem;
                padding: 6px;
            }

            .trial-counter h4 {
                font-size: 1rem;
            }

            .trial-counter #trial-countdown {
                font-size: 1rem;
            }

            .trial-counter p {
                font-size: 0.8rem;
            }
        }
    </style>
</head>
<body>
    <div class="background"></div>
    <div class="particles" id="particles-js"></div>

    <div class="dashboard-container">
        <?php if ($error_message): ?>
            <div class="alert alert-danger text-center">
                <?php echo $error_message; ?>
            </div>
        <?php endif; ?>

        <?php if ($activation_data['status'] === 'not_activated' && !$trial_expired): ?>
            <div class="trial-counter">
                <h4>فترة تجريبية: الوقت المتبقي</h4>
                <div id="trial-countdown">
                    <span id="days"><?php echo $remaining_time['days']; ?></span> أيام 
                    <span id="hours"><?php echo $remaining_time['hours']; ?></span> ساعات 
                    <span id="minutes"><?php echo $remaining_time['minutes']; ?></span> دقائق 
                    <span id="seconds"><?php echo $remaining_time['seconds']; ?></span> ثواني
                </div>
                <p>يرجى تفعيل النسخة قبل انتهاء الفترة التجريبية! <a href="activation.php" class="text-white">اضغط هنا للتفعيل</a></p>
            </div>
        <?php endif; ?>

        <div class="header">
            <img src="logo.png" alt="Astra Logo" class="logo" id="logo">
            <h1>Astra</h1>
        </div>

        <nav class="top-nav navbar navbar-expand-lg">
            <div class="container-fluid">
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNav">
                    <ul class="navbar-nav">
                        <li class="nav-item dropdown">
                            <a class="nav-link nav-suppliers dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                                <i class="fas fa-truck"></i> الموردين
                            </a>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item dropdown-item-suppliers check-permission" href="suppliers.php" target="_blank" data-screen="suppliers"><i class="fas fa-truck-loading"></i> الموردين</a></li>
                                                                <li><a class="dropdown-item dropdown-item-clients check-permission" href="suppliers_reports.php" target="_blank" data-screen="customers"><i class="fas fa-users"></i> تقارير الموردين</a></li>

                            </ul>
                        </li>
                        <li class="nav-item dropdown">
                            <a class="nav-link nav-clients dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                                <i class="fas fa-user-friends"></i> العملاء
                            </a>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item dropdown-item-clients check-permission" href="clients.php" target="_blank" data-screen="customers"><i class="fas fa-users"></i> العملاء</a></li>

                                <li><a class="dropdown-item dropdown-item-clients check-permission" href="clients_reports.php" target="_blank" data-screen="customers"><i class="fas fa-users"></i> تقارير العملاء</a></li>

                            </ul>
                        </li>
                        <li class="nav-item dropdown">
                            <a class="nav-link nav-employees dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                                <i class="fas fa-users"></i> الموظفين
                            </a>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item dropdown-item-employee-management check-permission" href="employee_management.php" target="_blank" data-screen="employee_management"><i class="fas fa-user-tie"></i> إدارة موظف</a></li>
                                <li><a class="dropdown-item dropdown-item-salary-payments check-permission" href="salary_payments.php" target="_blank" data-screen="salary_payment"><i class="fas fa-money-check-alt"></i> دفع رواتب</a></li>
                                <li><a class="dropdown-item dropdown-item-employee-report check-permission" href="employee_report.php" target="_blank" data-screen="employee_report"><i class="fas fa-chart-bar"></i> تقرير الموظفين</a></li>
                            </ul>
                        </li>
                        <li class="nav-item dropdown">
                            <a class="nav-link nav-items dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                                <i class="fas fa-boxes"></i> الأصناف
                            </a>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item dropdown-item-items check-permission" href="add_item.php" target="_blank" data-screen="items"><i class="fas fa-box"></i> الأصناف</a></li>
                                <li><a class="dropdown-item dropdown-item-categories check-permission" href="categories.php" target="_blank" data-screen="categories"><i class="fas fa-tags"></i> التصنيفات</a></li>
                                <li><a class="dropdown-item dropdown-item-units check-permission" href="units.php" target="_blank" data-screen="units"><i class="fas fa-ruler"></i> الوحدات</a></li>
                                <li><a class="dropdown-item dropdown-item-barcode check-permission" href="barcode_print.php" target="_blank" data-screen="barcode_printing"><i class="fas fa-barcode"></i> طباعة الباركود</a></li>
                                <li><a class="dropdown-item dropdown-item-item-movement check-permission" href="item_movement.php" target="_blank" data-screen="item_movement"><i class="fas fa-exchange-alt"></i> حركة صنف</a></li>
                            </ul>
                        </li>
                        <li class="nav-item dropdown">
                            <a class="nav-link nav-sales dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                                <i class="fas fa-chart-line"></i> المبيعات
                            </a>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item dropdown-item-sales-invoice check-permission" href="sales_invoice.php" target="_blank" data-screen="sales_invoice"><i class="fas fa-file-invoice"></i> فاتورة مبيعات</a></li>
                                <li><a class="dropdown-item dropdown-item-sales-invoices check-permission" href="sales_invoices.php" target="_blank" data-screen="sales_invoices"><i class="fas fa-file-alt"></i> فواتير البيع</a></li>
                                <li><a class="dropdown-item dropdown-item-pending-invoices check-permission" href="pending_invoices.php" target="_blank" data-screen="pending_invoices"><i class="fas fa-pause-circle"></i> فواتير معلقة</a></li>
                                <li><a class="dropdown-item dropdown-item-sales-return check-permission" href="sales_return.php" target="_blank" data-screen="sales_return"><i class="fas fa-undo"></i> مرتجع بيع</a></li>
                                <li><a class="dropdown-item dropdown-item-sales-return-invoices check-permission" href="sales_return_invoices.php" target="_blank" data-screen="sales_return_invoices"><i class="fas fa-file-import"></i> فواتير مرتجع البيع</a></li>
                            </ul>
                        </li>


                        <li class="nav-item dropdown">
                            <a class="nav-link nav-sales dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                                <i class="fas fa-chart-line"></i> المبيعات بالتقسيط
                            </a>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item dropdown-item-sales-invoice check-permission" href="installment_sales.php" target="_blank" data-screen="installment_sales"><i class="fas fa-file-invoice"></i> فاتورة مبيعات بالتقسيط</a></li>
                                <li><a class="dropdown-item dropdown-item-sales-invoices check-permission" href="manage_installments.php" target="_blank" data-screen="manage_installments"><i class="fas fa-file-alt"></i> فواتير البيع بالتقسيط</a></li>
                                <li><a class="dropdown-item dropdown-item-sales-invoices check-permission" href="completed_installments.php" target="_blank" data-screen="completed_installments.php"><i class="fas fa-file-alt"></i> فواتير التقسيط المنتهية</a></li>

                                
                            </ul>
                        </li>





                        <li class="nav-item dropdown">
                            <a class="nav-link nav-purchases dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                                <i class="fas fa-shopping-cart"></i> المشتريات
                            </a>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item dropdown-item-purchase-invoice check-permission" href="purchase_invoice.php" target="_blank" data-screen="purchase_invoice"><i class="fas fa-file-invoice-dollar"></i> فاتورة شراء</a></li>
                                <li><a class="dropdown-item dropdown-item-purchase-invoices check-permission" href="purchase_invoices.php" target="_blank" data-screen="purchase_invoices"><i class="fas fa-file-alt"></i> فواتير الشراء</a></li>
                                <li><a class="dropdown-item dropdown-item-purchase-return check-permission" href="purchase_return.php" target="_blank" data-screen="purchase_return"><i class="fas fa-undo"></i> مرتجع شراء</a></li>
                                <li><a class="dropdown-item dropdown-item-purchase-return-invoices check-permission" href="purchase_return_invoices.php" target="_blank" data-screen="purchase_return_invoices"><i class="fas fa-file-import"></i> فواتير مرتجع الشراء</a></li>
                            </ul>
                        </li>
                        <li class="nav-item dropdown">
                            <a class="nav-link nav-treasury dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                                <i class="fas fa-money-bill-wave"></i> الخزنة
                            </a>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item dropdown-item-treasury check-permission" href="treasury.php" target="_blank" data-screen="safe"><i class="fas fa-vault"></i> الخزنة</a></li>
                                <li><a class="dropdown-item dropdown-item-treasury-manage check-permission" href="treasury_manage.php" target="_blank" data-screen="safe_add_edit"><i class="fas fa-edit"></i> إضافة وتعديل خزنة</a></li>
                                <li><a class="dropdown-item dropdown-item-treasury-transfer check-permission" href="treasury_transfer.php" target="_blank" data-screen="safe_transfer"><i class="fas fa-exchange-alt"></i> تحويل مبلغ من خزنة</a></li>
                                <li><a class="dropdown-item dropdown-item-daily-revenue check-permission" href="daily_revenue.php" target="_blank" data-screen="daily_revenue"><i class="fas fa-chart-line"></i> الإيراد اليومي</a></li>
                                <li><a class="dropdown-item dropdown-item-expenses check-permission" href="expenses.php" target="_blank" data-screen="expenses"><i class="fas fa-money-bill-alt"></i> المصروفات</a></li>
                                <li><a class="dropdown-item dropdown-item-expense-types check-permission" href="expense_types.php" target="_blank" data-screen="expense_types"><i class="fas fa-list-alt"></i> أنواع المصروفات</a></li>
                            </ul>
                        </li>
                        <li class="nav-item dropdown">
                            <a class="nav-link nav-stores dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                                <i class="fas fa-store"></i> المخازن
                            </a>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item dropdown-item-store-add check-permission" href="store_add.php" target="_blank" data-screen="add_store"><i class="fas fa-plus-square"></i> إضافة مخزن</a></li>
                                <li><a class="dropdown-item dropdown-item-store-transfer check-permission" href="store_transfer.php" target="_blank" data-screen="store_transfer"><i class="fas fa-exchange-alt"></i> التحويل بين المخازن</a></li>
                                <li><a class="dropdown-item dropdown-item-store-inventory check-permission" href="store_inventory.php" target="_blank" data-screen="store_inventory"><i class="fas fa-warehouse"></i> جرد المخازن</a></li>
                            </ul>
                        </li>
                        <li class="nav-item dropdown">
                            <a class="nav-link nav-settings dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                                <i class="fas fa-cogs"></i> إعدادات
                            </a>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item dropdown-item-settings check-permission" href="settings.php" target="_blank" data-screen="settings"><i class="fas fa-tools"></i> إعدادات البرنامج</a></li>
                                <li><a class="dropdown-item dropdown-item-users check-permission" href="users.php" target="_blank" data-screen="users"><i class="fas fa-users-cog"></i> المستخدمين</a></li>
                                <li><a class="dropdown-item dropdown-item-backup check-permission" href="backup.php" target="_blank" data-screen="backup"><i class="fas fa-database"></i> نسخة احتياطية</a></li>
                                <li><a class="dropdown-item dropdown-item-activation check-permission" href="activation.php" target="_blank" data-screen="activation"><i class="fas fa-key"></i> تفعيل النسخة</a></li>
                            </ul>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>

        <div class="sidebar">
            <i class="fas fa-user-circle"></i>
            <div class="welcome">مرحبًا بك</div>
            <div class="username"><?php echo htmlspecialchars($user_name); ?></div>
            <button class="toggle-theme" onclick="toggleTheme()">تبديل الشكل</button>
        </div>

        <div class="welcome-sidebar">
            <i class="fas fa-handshake"></i>
            <div class="welcome-text">أهلاً بك في إدارة المبيعات Astra</div>
            <div class="daily-phrase" id="daily-phrase"></div>
        </div>

        <div class="ticker">
            <div class="ticker-content">
                <?php if (!empty($low_stock_items)): ?>
                    <?php foreach ($low_stock_items as $item): ?>
                        <span><?php echo htmlspecialchars($item['name']); ?> - تحذير: وصل للحد الأدنى</span>
                    <?php endforeach; ?>
                <?php else: ?>
                    <span>لا توجد أصناف وصلت للحد الأدنى</span>
                <?php endif; ?>
            </div>
        </div>

        <div class="shortcuts">
            <div class="shortcut-row">
                <a href="add_item.php" target="_blank" class="shortcut-card card-items check-permission" data-screen="items">
                    <i class="fas fa-boxes"></i>
                    <h3>الأصناف</h3>
                </a>
                <a href="sales_invoice.php" target="_blank" class="shortcut-card card-sales-invoice check-permission" data-screen="sales_invoice">
                    <i class="fas fa-file-invoice"></i>
                    <h3>فاتورة بيع</h3>
                </a>




                
                <a href="purchase_invoice.php" target="_blank" class="shortcut-card card-purchase-invoice check-permission" data-screen="purchase_invoice">
                    <i class="fas fa-file-invoice-dollar"></i>
                    <h3>فاتورة شراء</h3>
                </a>
                
                
                
                                <a href="installment_sales.php" target="_blank" class="shortcut-card card-sales-invoice check-permission" data-screen="sales_invoice">
                    <i class="fas fa-file-invoice"></i>
                    <h3>فاتورة بيع بالتقسيط</h3>
                </a>
                
                
                
                <a href="item_search.php" target="_blank" class="shortcut-card card-item-search check-permission" data-screen="item_search">
                    <i class="fas fa-search"></i>
                    <h3>استعلام عن صنف</h3>
                </a>
                <a href="store_inventory.php" target="_blank" class="shortcut-card card-inventory check-permission" data-screen="inventory">
                    <i class="fas fa-warehouse"></i>
                    <h3>جرد المخزن</h3>
                </a>
            </div>
            <div class="shortcut-row">
                <a href="treasury.php" target="_blank" class="shortcut-card card-treasury check-permission" data-screen="safe">
                    <i class="fas fa-money-bill-wave"></i>
                    <h3>الخزنة</h3>
                </a>
                <a href="store_add.php" target="_blank" class="shortcut-card card-stores check-permission" data-screen="stores">
                    <i class="fas fa-store"></i>
                    <h3>المخازن</h3>
                </a>
                <a href="clients.php" target="_blank" class="shortcut-card card-clients check-permission" data-screen="customers">
                    <i class="fas fa-users"></i>
                    <h3>العملاء</h3>
                </a>
                <a href="suppliers.php" target="_blank" class="shortcut-card card-suppliers check-permission" data-screen="suppliers">
                    <i class="fas fa-truck"></i>
                    <h3>الموردين</h3>
                </a>
                <a href="logout.php" target="_blank" class="shortcut-card card-logout">
                    <i class="fas fa-sign-out-alt"></i>
                    <h3>خروج</h3>
                </a>
            </div>
            <div class="shortcut-row">
                <a href="shift.php" target="_blank" class="shortcut-card card-shift-close check-permission" data-screen="shift_close">
                    <i class="fas fa-lock"></i>
                    <h3>فتح الوردية</h3>
                </a>
                <a href="contact_us.php" target="_blank" class="shortcut-card card-contact check-permission" data-screen="contact_us">
                    <i class="fas fa-phone"></i>
                    <h3>اتصل بنا</h3>
                </a>
            </div>
        </div>

        <div class="footer">
            <span id="date-time"></span>
        </div>
    </div>

    <!-- Modal لعرض رسالة الصلاحية -->
    <div class="modal fade" id="permissionModal" tabindex="-1" aria-labelledby="permissionModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="permissionModalLabel">تنبيه</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    ليس لديك صلاحيات للوصول إلى هذه الشاشة.
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">إغلاق</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/particles.js@2.0.0/particles.min.js"></script>
    <script>
        let particlesConfig = {
            "particles": {
                "number": { "value": 120, "density": { "enable": true, "value_area": 800 } },
                "color": { "value": "#ffffff" },
                "shape": { "type": "circle" },
                "opacity": { "value": 0.5, "random": true },
                "size": { "value": 3, "random": true },
                "line_linked": {
                    "enable": true,
                    "distance": 150,
                    "color": "#4169E1",
                    "opacity": 0.4,
                    "width": 1
                },
                "move": { "enable": true, "speed": 4, "direction": "none", "random": true }
            },
            "interactivity": {
                "detect_on": "canvas",
                "events": {
                    "onhover": { "enable": true, "mode": "repulse" },
                    "onclick": { "enable": true, "mode": "push" }
                }
            },
            "retina_detect": true
        };

        particlesJS("particles-js", particlesConfig);

        function updateDateTime() {
            const now = new Date();
            const days = ['الأحد', 'الإثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'];
            const day = days[now.getDay()];
            const date = now.toLocaleDateString('ar-EG');
            const time = now.toLocaleTimeString('ar-EG');
            document.getElementById('date-time').textContent = `${day}، ${date} - ${time}`;
        }
        setInterval(updateDateTime, 1000);
        updateDateTime();

        function toggleTheme() {
            const body = document.body;
            body.classList.toggle('dark-theme');
            if (body.classList.contains('dark-theme')) {
                particlesConfig.particles.color.value = "#E74C3C";
                particlesConfig.particles.line_linked.color = "#E74C3C";
                particlesConfig.particles.shape.type = "star";
            } else {
                particlesConfig.particles.color.value = "#ffffff";
                particlesConfig.particles.line_linked.color = "#4169E1";
                particlesConfig.particles.shape.type = "circle";
            }
            particlesJS("particles-js", particlesConfig);
        }

        const dailyPhrases = [
            "فرصة جديدة", "عميل محتمل", "هدف يومي", "زيادة الأرباح", "خدمة ممتازة",
            "جودة مضمونة", "عرض خاص", "سعر مناسب", "مكافأة مجزية", "تحقيق النجاح",
            "ولاء العملاء", "تطوير مستمر", "مهارات بيعية", "كسب الثقة", "مبيعات مرتفعة",
            "فريق ناجح", "علاقات قوية", "خطط تسويقية", "تحليل السوق", "نمو سريع",
            "تحقيق الأهداف", "ابتسامة دائمة", "أسلوب مقنع", "طلب متزايد", "منتج مميز",
            "نجاح مضمون", "تحفيز ذاتي", "عرض مغري", "رضا العميل", "بيع ذكي"
        ];

        function updateDailyPhrase() {
            const now = new Date();
            const startOfYear = new Date(now.getFullYear(), 0, 0);
            const diff = now - startOfYear;
            const oneDay = 1000 * 60 * 60 * 24;
            const dayOfYear = Math.floor(diff / oneDay);
            const phraseIndex = dayOfYear % dailyPhrases.length;
            document.getElementById('daily-phrase').textContent = dailyPhrases[phraseIndex];
        }
        updateDailyPhrase();

        // التحقق من الصلاحيات عند الضغط على الروابط
        document.addEventListener('click', function(e) {
            const link = e.target.closest('.check-permission');
            if (link) {
                e.preventDefault();
                const href = link.getAttribute('href');
                const dataScreen = link.getAttribute('data-screen');
                let screen = dataScreen || (href ? href.substring(href.lastIndexOf('/') + 1) : '');

                console.log('Clicked link:', link);
                console.log('href:', href);
                console.log('data-screen:', dataScreen);
                console.log('Extracted screen:', screen);

                if (!screen || screen.trim() === '') {
                    console.error('Screen value is empty or invalid', { href: href, dataScreen: dataScreen });
                    alert('حدث خطأ: لم يتم استخراج اسم الشاشة بشكل صحيح.');
                    return;
                }

                const xhr = new XMLHttpRequest();
                xhr.open('POST', 'check_permission.php', true);
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200) {
                            try {
                                const response = JSON.parse(xhr.responseText);
                                console.log('Permission response:', response);
                                if (response.hasPermission) {
                                    window.open(href, link.target || '_self');
                                } else {
                                    const permissionModal = new bootstrap.Modal(document.getElementById('permissionModal'));
                                    permissionModal.show();
                                }
                            } catch (error) {
                                console.error('Error parsing JSON:', error);
                                alert('حدث خطأ أثناء التحقق من الصلاحيات: ' + error.message);
                            }
                        } else {
                            console.error('AJAX request failed with status:', xhr.status);
                            alert('فشل الاتصال بالخادم. تحقق من check_permission.php');
                        }
                    }
                };
                xhr.onerror = function() {
                    console.error('AJAX request error');
                    alert('خطأ في الاتصال بالخادم');
                };
                console.log('Sending AJAX request with screen:', screen);
                const formData = new FormData();
                formData.append('screen', screen);
                xhr.send(formData);
            } else {
                console.log('No .check-permission link found for this click');
            }
        });

        // تحديث العداد التنازلي
        function updateTrialCountdown() {
            const daysElement = document.getElementById('days');
            const hoursElement = document.getElementById('hours');
            const minutesElement = document.getElementById('minutes');
            const secondsElement = document.getElementById('seconds');

            if (daysElement && hoursElement && minutesElement && secondsElement) {
                let days = parseInt(daysElement.textContent);
                let hours = parseInt(hoursElement.textContent);
                let minutes = parseInt(minutesElement.textContent);
                let seconds = parseInt(secondsElement.textContent);

                if (days === 0 && hours === 0 && minutes === 0 && seconds === 0) {
                    window.location.href = 'activation.php'; // إعادة توجيه عند انتهاء الوقت
                    return;
                }

                seconds--;
                if (seconds < 0) {
                    seconds = 59;
                    minutes--;
                    if (minutes < 0) {
                        minutes = 59;
                        hours--;
                        if (hours < 0) {
                            hours = 23;
                            days--;
                        }
                    }
                }

                daysElement.textContent = days;
                hoursElement.textContent = hours < 10 ? '0' + hours : hours;
                minutesElement.textContent = minutes < 10 ? '0' + minutes : minutes;
                secondsElement.textContent = seconds < 10 ? '0' + seconds : seconds;
            }
        }

        if (document.getElementById('trial-countdown')) {
            setInterval(updateTrialCountdown, 1000);
        }
    </script>
</body>
</html>