<?php
session_start();

// التحقق من تسجيل الدخول
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

// تضمين ملف الاتصال بقاعدة البيانات
require_once 'db_connect.php';

// التأكد من أن الاتصال ناجح
if (!isset($conn) || !$conn) {
    die("فشل الاتصال بقاعدة البيانات. تحقق من ملف db_connect.php.");
}

// تهيئة $_SESSION['current_items'] كمصفوفة فارغة إذا لم يكن محددًا
if (!isset($_SESSION['current_items']) || !is_array($_SESSION['current_items'])) {
    $_SESSION['current_items'] = [];
}

// التحقق من وجود وردية مفتوحة
$active_shift = null;
try {
    $stmt = $conn->prepare("SELECT id FROM shifts WHERE user_id = :user_id AND status = 'open' LIMIT 1");
    $stmt->execute([':user_id' => $_SESSION['user_id']]);
    $active_shift = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching active shift: " . $e->getMessage());
    header("Location: shift.php?error=حدث خطأ أثناء التحقق من الوردية");
    exit();
}

if (!$active_shift || !isset($active_shift['id'])) {
    header("Location: shift.php?error=يرجى فتح وردية أولاً!");
    exit();
}

// جلب بيانات المحل
$store_settings = [];
try {
    $stmt = $conn->query("SELECT * FROM settings LIMIT 1");
    $store_settings = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
} catch (PDOException $e) {
    error_log("Error fetching store settings: " . $e->getMessage());
    $store_settings = ['store_name' => 'Astra', 'phone' => '', 'address' => '', 'logo' => ''];
}

// جلب اسم المستخدم الحالي
$user_name = $_SESSION['user_name'] ?? '';
$user_id = $_SESSION['user_id'];
if (empty($user_name)) {
    try {
        $stmt = $conn->prepare("SELECT username FROM users WHERE id = :user_id");
        $stmt->execute([':user_id' => $user_id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        if (!empty($user) && isset($user['username'])) {
            $user_name = $user['username'];
            $_SESSION['user_name'] = $user_name;
        }
    } catch (PDOException $e) {
        error_log("Error fetching user name: " . $e->getMessage());
        $user_name = 'مستخدم غير محدد';
    }
}

// جلب المخازن
$stores = [];
try {
    $stores = $conn->query("SELECT id, name FROM stores")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching stores: " . $e->getMessage());
    $stores[] = ['id' => 1, 'name' => 'المخزن الافتراضي'];
}

// جلب الخزنات
$treasuries = [];
try {
    $treasuries = $conn->query("SELECT id, name FROM treasuries")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching treasuries: " . $e->getMessage());
    $treasuries[] = ['id' => 1, 'name' => 'الخزنة الافتراضية'];
}

// جلب العملاء
$clients = [];
try {
    $clients = $conn->query("SELECT id, name FROM clients")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching clients: " . $e->getMessage());
    $clients[] = ['id' => 1, 'name' => 'عميل افتراضي'];
}

// جلب التصنيفات
$categories = [];
try {
    $categories = $conn->query("SELECT id, name FROM categories")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching categories: " . $e->getMessage());
    $categories = [];
}

// جلب الأصناف
$items = [];
try {
    $items = $conn->query("SELECT id, name, barcode, retail_price, wholesale_price, quantity FROM items")->fetchAll(PDO::FETCH_ASSOC) ?: [];
    if (empty($items)) {
        error_log("No items found in database. Consider adding items.");
    }
} catch (PDOException $e) {
    error_log("Error fetching items: " . $e->getMessage());
    $items = [];
}

// إنشاء خيارات القائمة المنسدلة للأصناف
$itemOptions = '';
if (!empty($items) && is_array($items)) {
    foreach ($items as $item) {
        $itemOptions .= '<option value="' . $item['id'] . '" data-barcode="' . ($item['barcode'] ?? '') . '" data-retail-price="' . ($item['retail_price'] ?? 0) . '" data-wholesale-price="' . ($item['wholesale_price'] ?? 0) . '" data-quantity="' . ($item['quantity'] ?? 0) . '">' . htmlspecialchars($item['name'] ?? '') . '</option>';
    }
} else {
    $itemOptions = '<option value="">لا توجد أصناف متاحة</option>';
}

// رقم الفاتورة الجديد
$invoice_number = 1;
try {
    $last_invoice = $conn->query("SELECT MAX(id) as last_id FROM sales_invoices")->fetch(PDO::FETCH_ASSOC);
    $invoice_number = ($last_invoice['last_id'] ? $last_invoice['last_id'] + 1 : 1);
} catch (PDOException $e) {
    error_log("Error fetching last invoice: " . $e->getMessage());
}

// إدارة الفواتير المعلقة
if (!isset($_SESSION['pending_invoices'])) {
    $_SESSION['pending_invoices'] = [];
}

// استعادة فاتورة معلقة
$pending = null;
if (isset($_GET['restore_invoice']) && isset($_SESSION['pending_invoices'][$_GET['restore_invoice']])) {
    $pending = $_SESSION['pending_invoices'][$_GET['restore_invoice']];
    $_SESSION['current_items'] = $pending['items_data'] ?? [];
    $invoice_number = $_GET['restore_invoice'];
    unset($_SESSION['pending_invoices'][$_GET['restore_invoice']]);
    error_log("Restored pending invoice #" . $_GET['restore_invoice']);
}

// تحديث $_SESSION['current_items'] إذا كان هناك بيانات في POST
if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_POST['items_data'])) {
    $_SESSION['current_items'] = json_decode($_POST['items_data'], true) ?: [];
}

$success_message = '';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $store_id = $_POST['store_id'] ?? 1;
    $treasury_id = $_POST['treasury_id'] ?? 1;
    $client_id = $_POST['client_id'] ?? 1;
    $payment_type = $_POST['payment_type'] ?? 'cash';
    $discount_value = $_POST['discount_value'] ?? 0;
    $discount_type = $_POST['discount_type'] ?? 'fixed';
    $paid_amount = $_POST['paid_amount'] ?? 0;
    $items_data = json_decode($_POST['items_data'], true);

    if (empty($items_data) || !is_array($items_data)) {
        $success_message = "لا يمكن حفظ فاتورة بدون أصناف!";
    } else {
        $total = 0;
        foreach ($items_data as $item) {
            $total += $item['quantity'] * $item['price'];
        }

        if ($discount_type === 'percentage') {
            $discount = ($total * $discount_value) / 100;
        } else {
            $discount = $discount_value;
        }
        $final_total = $total - $discount;

        if ($payment_type === 'cash') {
            $paid_amount = $final_total;
        } else {
            $paid_amount = floatval($paid_amount);
        }
        $remaining_amount = $payment_type === 'credit' ? $final_total - $paid_amount : 0;

        if (isset($_POST['save_invoice'])) {
            try {
                $conn->beginTransaction();

                error_log("Saving invoice with values: " . json_encode([
                    'invoice_number' => $invoice_number,
                    'store_id' => $store_id,
                    'treasury_id' => $treasury_id,
                    'client_id' => $client_id,
                    'user_id' => $user_id,
                    'payment_type' => $payment_type,
                    'total' => $total,
                    'discount' => $discount,
                    'final_total' => $final_total,
                    'paid_amount' => $paid_amount,
                    'remaining_amount' => $remaining_amount,
                    'shift_id' => $active_shift['id'],
                    'items_data' => $items_data
                ]));

                if (empty($invoice_number) || empty($items_data)) {
                    throw new Exception("رقم الفاتورة أو العناصر مفقودة");
                }

                $stmt = $conn->prepare("INSERT INTO sales_invoices (invoice_number, store_id, treasury_id, client_id, user_id, payment_type, total, discount, final_total, paid_amount, remaining_amount, date, shift_id) VALUES (:invoice_number, :store_id, :treasury_id, :client_id, :user_id, :payment_type, :total, :discount, :final_total, :paid_amount, :remaining_amount, NOW(), :shift_id)");
                $stmt->execute([
                    ':invoice_number' => $invoice_number,
                    ':store_id' => $store_id,
                    ':treasury_id' => $treasury_id,
                    ':client_id' => $client_id,
                    ':user_id' => $user_id,
                    ':payment_type' => $payment_type,
                    ':total' => $total,
                    ':discount' => $discount,
                    ':final_total' => $final_total,
                    ':paid_amount' => $paid_amount,
                    ':remaining_amount' => $remaining_amount,
                    ':shift_id' => $active_shift['id']
                ]);

                $invoice_id = $conn->lastInsertId();
                error_log("Invoice inserted successfully with ID: " . $invoice_id);

                foreach ($items_data as $item) {
                    $stmt = $conn->prepare("SELECT quantity FROM items WHERE id = :item_id");
                    $stmt->execute([':item_id' => $item['id']]);
                    $current_quantity = $stmt->fetchColumn();

                    if ($current_quantity === false || $current_quantity < $item['quantity']) {
                        throw new Exception("الكمية غير كافية للصنف: " . ($item['name'] ?? $item['id']));
                    }

                    $stmt = $conn->prepare("INSERT INTO sales_invoice_items (invoice_id, item_id, quantity, price) VALUES (:invoice_id, :item_id, :quantity, :price)");
                    $stmt->execute([
                        ':invoice_id' => $invoice_id,
                        ':item_id' => $item['id'],
                        ':quantity' => $item['quantity'],
                        ':price' => $item['price']
                    ]);

                    $stmt = $conn->prepare("UPDATE items SET quantity = quantity - :sold_quantity WHERE id = :item_id");
                    $stmt->execute([
                        ':sold_quantity' => $item['quantity'],
                        ':item_id' => $item['id']
                    ]);
                }

                $transaction_type = ($payment_type === 'cash') ? 'income' : 'pending';
                $description = $payment_type === 'cash' ? "دفع نقدي لفاتورة رقم $invoice_number" : "دفع آجل لفاتورة رقم $invoice_number";

                $stmt = $conn->prepare("INSERT INTO treasury_transactions (treasury_id, invoice_id, transaction_type, amount, description, date) VALUES (:treasury_id, :invoice_id, :transaction_type, :amount, :description, NOW())");
                $stmt->execute([
                    ':treasury_id' => $treasury_id,
                    ':invoice_id' => $invoice_id,
                    ':transaction_type' => $transaction_type,
                    ':amount' => $final_total,
                    ':description' => $description
                ]);

                if ($payment_type === 'cash') {
                    $stmt = $conn->prepare("UPDATE treasuries SET current_balance = current_balance + :final_total WHERE id = :treasury_id");
                    $stmt->execute([
                        ':final_total' => $final_total,
                        ':treasury_id' => $treasury_id
                    ]);
                    error_log("Treasury updated with final_total: $final_total for treasury_id: $treasury_id");
                }

                if ($payment_type === 'credit' && $remaining_amount > 0) {
                    $stmt = $conn->prepare("UPDATE clients SET previous_debt = previous_debt + :remaining_amount WHERE id = :client_id");
                    $stmt->execute([':remaining_amount' => $remaining_amount, ':client_id' => $client_id]);
                }

                $conn->commit();

                header('Content-Type: application/json');
                echo json_encode([
                    'status' => 'success',
                    'message' => 'تم حفظ الفاتورة بنجاح',
                    'invoice_id' => $invoice_id,
                    'invoice_number' => $invoice_number
                ]);
                unset($_SESSION['current_items']);
                $invoice_number++;
                exit();
            } catch (Exception $e) {
                $conn->rollBack();
                error_log("Error saving invoice: " . $e->getMessage());

                header('Content-Type: application/json');
                echo json_encode([
                    'status' => 'error',
                    'message' => 'فشل حفظ الفاتورة: ' . $e->getMessage()
                ]);
                exit();
            }
        } elseif (isset($_POST['suspend'])) {
            if (empty($items_data)) {
                $success_message = "لا يمكن تعليق فاتورة فارغة!";
            } else {
                try {
                    $total = 0;
                    foreach ($items_data as $item) {
                        $total += $item['quantity'] * $item['price'];
                    }

                    if ($discount_type === 'percentage') {
                        $discount = ($total * $discount_value) / 100;
                    } else {
                        $discount = $discount_value;
                    }
                    $final_total = $total - $discount;
                    $remaining_amount = $payment_type === 'credit' ? $final_total - $paid_amount : 0;

                    $_SESSION['pending_invoices'][$invoice_number] = [
                        'store_id' => $store_id,
                        'treasury_id' => $treasury_id,
                        'client_id' => $client_id,
                        'user_id' => $user_id,
                        'payment_type' => $payment_type,
                        'discount_value' => $discount_value,
                        'discount_type' => $discount_type,
                        'paid_amount' => $paid_amount,
                        'items_data' => $items_data,
                        'total' => $total,
                        'discount' => $discount,
                        'final_total' => $final_total,
                        'remaining_amount' => $remaining_amount,
                        'date' => date('Y-m-d'),
                        'shift_id' => $active_shift['id']
                    ];

                    header('Content-Type: application/json');
                    echo json_encode([
                        'status' => 'success',
                        'message' => 'تم تعليق الفاتورة بنجاح',
                        'invoice_number' => $invoice_number
                    ]);
                    unset($_SESSION['current_items']);
                    $invoice_number++;
                    exit();
                } catch (Exception $e) {
                    error_log("Error suspending invoice: " . $e->getMessage());
                    header('Content-Type: application/json');
                    echo json_encode([
                        'status' => 'error',
                        'message' => 'فشل تعليق الفاتورة: ' . $e->getMessage()
                    ]);
                    exit();
                }
            }
        }
    }
}
?>

<!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 href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.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;
            direction: rtl;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #2ECC71, #3498DB, #E74C3C);
            overflow-x: hidden;
            animation: gradientShift 10s ease infinite;
            background-size: 400% 400%;
        }

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

        .container-fluid {
            padding: 20px;
            height: 100vh;
            display: flex;
            flex-direction: row;
            gap: 20px;
        }

        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            transition: flex 0.3s ease;
        }

        .main-content.full-width {
            flex: 1 1 100%;
        }

        .card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            padding: 20px;
            margin-bottom: 20px;
            animation: fadeIn 1s ease-in-out;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        h2 {
            color: #2ECC71;
            font-weight: bold;
            text-align: center;
            margin-bottom: 20px;
            text-shadow: 0 0 5px rgba(46, 204, 113, 0.5);
        }

        .form-label {
            color: #3498DB;
            font-weight: bold;
            margin-bottom: 5px;
            display: flex;
            align-items: center;
            font-size: 0.9rem;
        }

        .form-label i {
            margin-left: 8px;
            color: #2ECC71;
        }

        .form-control, .form-select {
            border-radius: 10px;
            border: 2px solid #2ECC71;
            padding: 6px 10px;
            background: rgba(255, 255, 255, 0.8);
            transition: all 0.3s ease;
            box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.1);
            font-size: 0.9rem;
        }

        .form-control:focus, .form-select:focus {
            border-color: #3498DB;
            box-shadow: 0 0 10px rgba(52, 152, 219, 0.5), inset 0 2px 5px rgba(0, 0, 0, 0.1);
            background: #fff;
        }

        .select2-container--default .select2-selection--single {
            border: 2px solid #2ECC71;
            border-radius: 10px;
            background: rgba(255, 255, 255, 0.8);
            height: 38px;
            padding: 6px 10px;
        }

        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 26px;
            color: #333;
        }

        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 36px;
        }

        .select2-container--default .select2-selection--single:focus {
            border-color: #3498DB;
            box-shadow: 0 0 10px rgba(52, 152, 219, 0.5);
        }

        .select2-dropdown {
            border: 2px solid #2ECC71;
            border-radius: 10px;
            background: rgba(255, 255, 255, 0.95);
        }

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

        .select2-results__option--highlighted {
            background: rgba(46, 204, 113, 0.1) !important;
            color: #333 !important;
        }

        .btn {
            border-radius: 10px;
            padding: 6px 15px;
            font-weight: bold;
            transition: all 0.4s ease;
            position: relative;
            overflow: hidden;
            font-size: 0.9rem;
        }

        .btn-save {
            background: linear-gradient(45deg, #2ECC71, #27AE60);
            border: none;
            color: #fff;
        }

        .btn-save:hover {
            background: linear-gradient(45deg, #27AE60, #219653);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(46, 204, 113, 0.5);
        }

        .btn-cancel {
            background: linear-gradient(45deg, #E74C3C, #C0392B);
            border: none;
            color: #fff;
        }

        .btn-cancel:hover {
            background: linear-gradient(45deg, #C0392B, #A93226);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(231, 76, 60, 0.5);
        }

        .btn-price-type {
            background: linear-gradient(45deg, #F1C40F, #D4AC0D);
            border: none;
            color: #fff;
        }

        .btn-price-type:hover {
            background: linear-gradient(45deg, #D4AC0D, #B7950B);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(241, 196, 15, 0.5);
        }

        .btn-suspend {
            background: linear-gradient(45deg, #9B59B6, #8E44AD);
            border: none;
            color: #fff;
        }

        .btn-suspend:hover {
            background: linear-gradient(45deg, #8E44AD, #7D3C98);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(155, 89, 182, 0.5);
        }

        .btn-delete {
            border-radius: 10px;
            padding: 6px 15px;
            font-weight: bold;
            margin: 5px;
            transition: all 0.4s ease;
            background: linear-gradient(45deg, #3498DB, #2980B9);
            border: none;
            color: #fff;
            cursor: pointer;
        }

        .btn-delete:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.5);
        }

        .btn-toggle-sidebar {
            background: linear-gradient(45deg, #3498DB, #2980B9);
            border: none;
            color: #fff;
            padding: 8px 15px;
            border-radius: 10px;
            margin-bottom: 10px;
            cursor: pointer;
            font-weight: bold;
            transition: all 0.3s ease;
        }

        .btn-toggle-sidebar:hover {
            background: linear-gradient(45deg, #2980B9, #2471A3);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.5);
        }

        .btn i {
            margin-left: 8px;
        }

        .success-message {
            color: #2ECC71;
            font-weight: bold;
            text-align: center;
            margin-bottom: 20px;
            animation: fadeIn 0.5s ease-in-out;
        }

        .table {
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            width: 100%;
        }

        .table thead {
            background: #2ECC71;
            color: #fff;
        }

        .table tbody tr:hover {
            background: rgba(46, 204, 113, 0.1);
        }

        .total-box {
            background: linear-gradient(45deg, #E74C3C, #C0392B);
            color: #fff;
            padding: 15px 25px;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(231, 76, 60, 0.5);
            text-align: center;
            font-weight: bold;
            font-size: 1.5rem;
            position: fixed;
            bottom: 60px;
            right: 20px;
            z-index: 1000;
        }

        .remaining-box {
            background: linear-gradient(45deg, #F1C40F, #D4AC0D);
            color: #fff;
            padding: 10px 20px;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(241, 196, 15, 0.5);
            text-align: center;
            font-weight: bold;
            font-size: 1.2rem;
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 1000;
            display: none;
        }

        .shortcuts {
            position: fixed;
            bottom: 20px;
            left: 20px;
            z-index: 1000;
            font-size: 0.9rem;
        }

        .shortcut-text {
            padding: 5px 10px;
            border-radius: 10px;
            color: #fff;
            font-weight: bold;
            margin-right: 10px;
            display: inline-block;
        }

        .shortcut-f8 {
            background: linear-gradient(45deg, #2ECC71, #27AE60);
        }

        .shortcut-f5 {
            background: linear-gradient(45deg, #3498DB, #2980B9);
        }

        .shortcut-f9 {
            background: linear-gradient(45deg, #9B59B6, #8E44AD);
        }

        .shortcut-f10 {
            background: linear-gradient(45deg, #2ECC71, #27AE60);
        }

        .pending-invoices {
            position: fixed;
            bottom: 60px;
            left: 20px;
            z-index: 1000;
            font-size: 0.9rem;
        }

        .pending-invoice-btn {
            background: linear-gradient(45deg, #9B59B6, #8E44AD);
            border: none;
            color: #fff;
            padding: 5px 15px;
            border-radius: 10px;
            margin: 5px 0;
            cursor: pointer;
            font-weight: bold;
            transition: all 0.4s ease;
            display: block;
        }

        .pending-invoice-btn:hover {
            background: linear-gradient(45deg, #8E44AD, #7D3C98);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(155, 89, 182, 0.5);
        }

        .sidebar {
            width: 300px;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
            padding: 15px;
            max-height: 80vh;
            overflow-y: auto;
            position: sticky;
            top: 20px;
            transition: transform 0.3s ease;
        }

        .sidebar.hidden {
            transform: translateX(100%);
            display: none;
        }

        .sidebar h4 {
            color: #2ECC71;
            font-weight: bold;
            margin-bottom: 15px;
            text-align: center;
        }

        .category-btn, .item-btn {
            border-radius: 10px;
            padding: 8px 15px;
            font-weight: bold;
            margin: 5px 0;
            transition: all 0.3s ease;
            border: none;
            color: #fff;
            cursor: pointer;
            width: 100%;
            text-align: right;
        }

        .category-btn {
            background: linear-gradient(45deg, #3498DB, #2980B9);
        }

        .category-btn:hover, .category-btn.active {
            background: linear-gradient(45deg, #2980B9, #2471A3);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.5);
        }

        .item-btn {
            background: linear-gradient(45deg, #2ECC71, #27AE60);
        }

        .item-btn:hover {
            background: linear-gradient(45deg, #27AE60, #219653);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(46, 204, 113, 0.5);
        }

        .items-container {
            margin-top: 5px;
            margin-bottom: 10px;
            max-height: 200px;
            overflow-y: auto;
            display: none;
        }

        .items-container.active {
            display: block;
        }

        .payment-window {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 10000;
        }

        .payment-container {
            background: white;
            padding: 20px;
            border-radius: 10px;
            width: 300px;
            text-align: center;
        }

        .payment-container h3 {
            color: #2ECC71;
            margin-bottom: 20px;
        }

        .payment-input-group {
            margin: 15px 0;
        }

        .payment-input-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .payment-input-group input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 5px;
            text-align: center;
        }

        .payment-input-group input:focus {
            border-color: #2ECC71;
            outline: none;
        }

        .payment-buttons {
            display: flex;
            justify-content: space-between;
            margin-top: 20px;
        }

        .payment-buttons button {
            padding: 8px 15px;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        #printInvoiceBtn {
            background: #2ECC71;
        }

        #cancelPaymentBtn {
            background: #E74C3C;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="main-content">
            <div class="card">
                <h2><i class="fas fa-file-invoice me-2"></i> فاتورة بيع</h2>
                <?php if (isset($success_message)): ?>
                    <div class="success-message"><?php echo $success_message; ?></div>
                <?php endif; ?>
                <form method="POST" id="invoiceForm">
                    <div class="invoice-details row g-3">
                        <div class="col-md-2">
                            <label class="form-label"><i class="fas fa-store"></i> المخزن</label>
                            <select class="form-select" name="store_id" required>
                                <?php foreach ($stores as $store): ?>
                                    <option value="<?php echo $store['id']; ?>" <?php echo (isset($pending) && $pending['store_id'] == $store['id']) ? 'selected' : ($store['id'] == 1 ? 'selected' : ''); ?>>
                                        <?php echo htmlspecialchars($store['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label"><i class="fas fa-vault"></i> الخزنة</label>
                            <select class="form-select" name="treasury_id" required>
                                <?php foreach ($treasuries as $treasury): ?>
                                    <option value="<?php echo $treasury['id']; ?>" <?php echo (isset($pending) && $pending['treasury_id'] == $treasury['id']) ? 'selected' : ($treasury['id'] == 1 ? 'selected' : ''); ?>>
                                        <?php echo htmlspecialchars($treasury['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label"><i class="fas fa-barcode"></i> الباركود</label>
                            <input type="text" class="form-control" id="barcodeInput" placeholder="ادخل الباركود" value="<?php echo isset($pending) ? '' : ''; ?>">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label"><i class="fas fa-box"></i> الصنف</label>
                            <select class="form-select" id="itemSelect" style="width: 100%;">
                                <option value="">اختر الصنف</option>
                                <?php echo $itemOptions; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label"><i class="fas fa-shopping-cart"></i> نوع السعر</label>
                            <button type="button" class="btn btn-price-type" id="priceTypeBtn" onclick="togglePriceType()">سعر القطاعي</button>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label"><i class="fas fa-user"></i> المستخدم</label>
                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($user_name); ?>" readonly>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label"><i class="fas fa-hashtag"></i> رقم الفاتورة</label>
                            <input type="text" class="form-control" name="invoice_number" value="<?php echo $invoice_number; ?>" readonly>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label"><i class="fas fa-money-bill"></i> نوع الدفع</label>
                            <select class="form-select" name="payment_type" id="paymentType" onchange="togglePaidAmount()" required>
                                <option value="cash" <?php echo (isset($pending) && $pending['payment_type'] == 'cash') ? 'selected' : ''; ?>>نقدي</option>
                                <option value="credit" <?php echo (isset($pending) && $pending['payment_type'] == 'credit') ? 'selected' : ''; ?>>آجل</option>
                            </select>
                        </div>
                        <div class="col-md-2" id="paidAmountField" style="display: <?php echo (isset($pending) && $pending['payment_type'] == 'credit') ? 'block' : 'none'; ?>;">
                            <label class="form-label"><i class="fas fa-money-check"></i> المبلغ المدفوع</label>
                            <input type="number" step="0.01" class="form-control" name="paid_amount" id="paidAmount" value="<?php echo (isset($pending) && $pending['payment_type'] == 'credit') ? $pending['paid_amount'] : '0'; ?>" oninput="updateTotal()">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label"><i class="fas fa-calendar"></i> التاريخ</label>
                            <input type="date" class="form-control" name="date" value="<?php echo (isset($pending) ? $pending['date'] : date('Y-m-d')); ?>" readonly>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label"><i class="fas fa-user"></i> العميل</label>
                            <select class="form-select" name="client_id" id="clientSelect" required>
                                <?php foreach ($clients as $client): ?>
                                    <option value="<?php echo $client['id']; ?>" <?php echo (isset($pending) && $pending['client_id'] == $client['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($client['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label"><i class="fas fa-minus-circle"></i> الخصم</label>
                            <input type="number" step="0.01" class="form-control" name="discount_value" id="discountValue" placeholder="الخصم" value="<?php echo (isset($pending) ? $pending['discount_value'] : '0'); ?>" oninput="updateTotal()">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label"><i class="fas fa-percentage"></i> نوع الخصم</label>
                            <select class="form-select" name="discount_type" id="discountType" onchange="updateTotal()">
                                <option value="fixed" <?php echo (isset($pending) && $pending['discount_type'] == 'fixed') ? 'selected' : ''; ?>>جنيه</option>
                                <option value="percentage" <?php echo (isset($pending) && $pending['discount_type'] == 'percentage') ? 'selected' : ''; ?>>%</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <button type="button" class="btn btn-save" name="save_invoice" id="saveInvoiceBtn"><i class="fas fa-save"></i> حفظ الفاتورة</button>
                        </div>
                        <div class="col-md-2">
                            <button type="button" class="btn btn-cancel" onclick="window.location.href='dashboard.php'"><i class="fas fa-times"></i> إلغاء</button>
                        </div>
                        <div class="col-md-2">
                            <button type="button" class="btn btn-suspend" name="suspend" id="suspendInvoiceBtn"><i class="fas fa-pause"></i> تعليق الفاتورة</button>
                        </div>
                    </div>
                    <input type="hidden" name="items_data" id="itemsData">
                </form>

                <div class="table-responsive" style="max-height: 50vh; overflow-y: auto;">
                    <table class="table table-striped" id="itemsTable">
                        <thead>
                            <tr>
                                <th>الإجراء</th>
                                <th>اسم الصنف</th>
                                <th>الكمية</th>
                                <th>السعر</th>
                                <th>الإجمالي</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $current_items = isset($_SESSION['current_items']) && is_array($_SESSION['current_items']) ? $_SESSION['current_items'] : [];
                            if (!empty($current_items) && is_array($current_items)):
                                foreach ($current_items as $index => $item):
                            ?>
                                    <tr>
                                        <td>
                                            <button class="btn btn-delete" onclick="deleteItem(<?php echo $index; ?>)">
                                                <i class="fas fa-trash"></i> حذف
                                            </button>
                                        </td>
                                        <td><?php echo htmlspecialchars($item['name'] ?? ''); ?></td>
                                        <td><input type="number" class="form-control" value="<?php echo $item['quantity'] ?? 1; ?>" min="1" onchange="updateQuantity(<?php echo $index; ?>, this.value)"></td>
                                        <td><?php echo number_format($item['price'] ?? 0, 2); ?></td>
                                        <td><?php echo number_format($item['total'] ?? 0, 2); ?></td>
                                    </tr>
                            <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="5" style="text-align: center; color: #E74C3C;">لا توجد أصناف في الفاتورة.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="sidebar" id="sidebar">
            <button class="btn-toggle-sidebar" id="toggleSidebarBtn" onclick="toggleSidebar()">
                <i class="fas fa-eye-slash"></i> إخفاء اللوحة
            </button>
            <h4>التصنيفات والأصناف</h4>
            <?php if (!empty($categories)): ?>
                <?php foreach ($categories as $index => $category): ?>
                    <button class="category-btn" onclick="fetchItems(<?php echo $category['id']; ?>, this)" data-index="<?php echo $index; ?>">
                        <?php echo htmlspecialchars($category['name']); ?>
                    </button>
                    <div class="items-container" id="itemsContainer_<?php echo $category['id']; ?>">
                        <p style="color: #3498DB;">اختر تصنيفًا لعرض الأصناف.</p>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <p style="color: #E74C3C;">لا توجد تصنيفات متاحة.</p>
            <?php endif; ?>
        </div>

        <div class="total-box">
            الإجمالي: <span id="totalAmount"><?php echo isset($pending) && $pending['final_total'] ? number_format($pending['final_total'], 2) : '0.00'; ?></span> ج.م
        </div>
        <div class="remaining-box" id="remainingBox" style="display: <?php echo (isset($pending) && $pending['payment_type'] == 'credit') ? 'block' : 'none'; ?>;">
            المتبقي: <span id="remainingAmount"><?php echo isset($pending) && $pending['payment_type'] == 'credit' ? number_format($pending['remaining_amount'], 2) : '0.00'; ?></span> ج.م
        </div>

        <div class="shortcuts">
            <span class="shortcut-text shortcut-f8"><i class="fas fa-edit me-1"></i> تعديل الكمية: F8</span>
            <span class="shortcut-text shortcut-f5"><i class="fas fa-save me-1"></i> حفظ الفاتورة: F5</span>
            <span class="shortcut-text shortcut-f9"><i class="fas fa-pause me-1"></i> تعليق الفاتورة: F9</span>
            <span class="shortcut-text shortcut-f10"><i class="fas fa-eye me-1"></i> إظهار/إخفاء اللوحة: F10</span>
        </div>

        <div class="pending-invoices">
            <?php if (!empty($_SESSION['pending_invoices'])): ?>
                <?php foreach ($_SESSION['pending_invoices'] as $invoice_num => $invoice): ?>
                    <button class="pending-invoice-btn" onclick="window.location.href='sales_invoice.php?restore_invoice=<?php echo $invoice_num; ?>'">فاتورة معلقة #<?php echo $invoice_num; ?></button>
                <?php endforeach; ?>
            <?php else: ?>
                <p style="color: #9B59B6; font-size: 0.9rem;">لا توجد فواتير معلقة.</p>
            <?php endif; ?>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <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/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        let items = <?php echo json_encode(isset($_SESSION['current_items']) && is_array($_SESSION['current_items']) ? $_SESSION['current_items'] : []); ?>;
        let priceType = 'retail';
        let activeCategoryButton = null;
        let isSidebarVisible = true;

        document.addEventListener('DOMContentLoaded', () => {
            const barcodeInput = document.getElementById('barcodeInput');
            if (barcodeInput && (!document.activeElement || document.activeElement === document.body)) {
                barcodeInput.focus();
            }
            updateTable();

            document.getElementById('saveInvoiceBtn').addEventListener('click', submitForm);
            document.getElementById('suspendInvoiceBtn').addEventListener('click', submitForm);
            document.addEventListener('keydown', handleShortcuts);

            // تهيئة Select2 لقائمة الأصناف
            $('#itemSelect').select2({
                placeholder: "ابحث عن الصنف بالاسم أو الباركود",
                allowClear: true,
                dir: "rtl",
                minimumInputLength: 1,
                matcher: function(params, data) {
                    if (!params.term || params.term.trim() === '') {
                        return data;
                    }
                    const term = params.term.toLowerCase();
                    const itemName = data.text.toLowerCase();
                    const barcode = $(data.element).data('barcode')?.toString().toLowerCase() || '';
                    if (itemName.includes(term) || barcode.includes(term)) {
                        return data;
                    }
                    return null;
                }
            });

            // إضافة الصنف عند اختياره من Select2
            $('#itemSelect').on('select2:select', function(e) {
                addItem();
                $('#itemSelect').val('').trigger('change');
                const barcodeInput = document.getElementById('barcodeInput');
                if (barcodeInput && (!document.activeElement || document.activeElement === document.body)) {
                    barcodeInput.focus();
                }
            });

            // إعادة التركيز على حقل الباركود بعد إغلاق القائمة
            $('#itemSelect').on('select2:close', function(e) {
                const barcodeInput = document.getElementById('barcodeInput');
                if (barcodeInput && (!document.activeElement || document.activeElement === document.body)) {
                    barcodeInput.focus();
                }
            });
        });

        document.getElementById('barcodeInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                const barcode = this.value.trim();
                const itemSelect = document.getElementById('itemSelect');
                const options = itemSelect.options;

                for (let i = 0; i < options.length; i++) {
                    if (options[i].getAttribute('data-barcode') === barcode) {
                        itemSelect.selectedIndex = i;
                        addItem();
                        break;
                    }
                }
                this.value = '';
                if (!document.activeElement || document.activeElement === document.body) {
                    this.focus();
                }
            }
        });

        function addItem(itemId = null) {
            const itemSelect = document.getElementById('itemSelect');
            let selectedOption;

            if (itemId) {
                selectedOption = Array.from(itemSelect.options).find(opt => opt.value == itemId);
                if (!selectedOption) return;
            } else {
                selectedOption = itemSelect.options[itemSelect.selectedIndex];
            }

            const itemIdToAdd = selectedOption.value;
            if (!itemIdToAdd) return;

            const itemName = selectedOption.text;
            const retailPrice = parseFloat(selectedOption.getAttribute('data-retail-price') ?? '0') || 0;
            const wholesalePrice = parseFloat(selectedOption.getAttribute('data-wholesale-price') ?? '0') || 0;
            const availableQuantity = parseInt(selectedOption.getAttribute('data-quantity') ?? '0') || 0;
            const price = priceType === 'retail' ? retailPrice : wholesalePrice;

            if (availableQuantity <= 0) {
                alert('الكمية غير متاحة لهذا الصنف: ' + itemName);
                return;
            }

            const existingItem = items.find(item => item.id === itemIdToAdd);
            if (existingItem) {
                const newQuantity = existingItem.quantity + 1;
                if (newQuantity > availableQuantity) {
                    alert('الكمية المطلوبة غير متاحة لهذا الصنف: ' + itemName + '. الكمية المتاحة: ' + availableQuantity);
                    return;
                }
                existingItem.quantity = newQuantity;
                existingItem.total = existingItem.quantity * existingItem.price;
            } else {
                if (1 > availableQuantity) {
                    alert('الكمية المطلوبة غير متاحة لهذا الصنف: ' + itemName + '. الكمية المتاحة: ' + availableQuantity);
                    return;
                }
                items.push({ id: itemIdToAdd, name: itemName, quantity: 1, price: price, total: price });
            }

            updateTable();
            saveItemsToSession();
            const barcodeInput = document.getElementById('barcodeInput');
            if (barcodeInput && (!document.activeElement || document.activeElement === document.body)) {
                barcodeInput.focus();
            }
        }

        function updateQuantity(index, quantity) {
            if (isNaN(quantity) || quantity < 1) quantity = 1;
            const itemSelect = document.getElementById('itemSelect');
            const selectedOption = Array.from(itemSelect.options).find(opt => opt.value === items[index].id);
            const availableQuantity = parseInt(selectedOption?.getAttribute('data-quantity') ?? '0') || 0;

            quantity = parseInt(quantity);
            if (quantity > availableQuantity) {
                alert('الكمية المطلوبة غير متاحة لهذا الصنف: ' + items[index].name + '. الكمية المتاحة: ' + availableQuantity);
                quantity = availableQuantity;
            }

            items[index].quantity = quantity;
            items[index].total = items[index].quantity * items[index].price;
            updateTable();
            saveItemsToSession();
            const barcodeInput = document.getElementById('barcodeInput');
            if (barcodeInput && (!document.activeElement || document.activeElement === document.body)) {
                barcodeInput.focus();
            }
        }

        function deleteItem(index) {
            if (confirm('هل أنت متأكد من حذف هذا الصنف؟')) {
                items.splice(index, 1);
                updateTable();
                saveItemsToSession();
                const barcodeInput = document.getElementById('barcodeInput');
                if (barcodeInput && (!document.activeElement || document.activeElement === document.body)) {
                    barcodeInput.focus();
                }
            }
        }

        function updateTable() {
            const tbody = document.getElementById('itemsTable').getElementsByTagName('tbody')[0];
            tbody.innerHTML = '';

            let total = 0;
            items = items.filter(item => item.id && !isNaN(item.price) && !isNaN(item.quantity));
            items.forEach((item, index) => {
                if (isNaN(item.price) || isNaN(item.quantity)) return;
                item.total = item.quantity * item.price;
                total += item.total;
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>
                        <button class="btn btn-delete" onclick="deleteItem(${index})">
                            <i class="fas fa-trash"></i> حذف
                        </button>
                    </td>
                    <td>${item.name || ''}</td>
                    <td><input type="number" class="form-control" value="${item.quantity || 1}" min="1" onchange="updateQuantity(${index}, this.value)"></td>
                    <td>${Number(item.price || 0).toFixed(2)}</td>
                    <td>${Number(item.total || 0).toFixed(2)}</td>
                `;
                tbody.appendChild(row);
            });

            const discountValue = parseFloat(document.getElementById('discountValue').value) || 0;
            const discountType = document.getElementById('discountType').value || 'fixed';
            let finalTotal = total;
            if (discountType === 'percentage') {
                finalTotal -= (total * discountValue) / 100;
            } else {
                finalTotal -= discountValue;
            }
            finalTotal = Math.max(0, finalTotal);

            const paymentType = document.getElementById('paymentType').value || 'cash';
            let paidAmount = parseFloat(document.getElementById('paidAmount')?.value || 0);
            if (paymentType === 'cash') {
                paidAmount = finalTotal;
            }
            const remainingAmount = paymentType === 'credit' ? Math.max(0, finalTotal - paidAmount) : 0;

            document.getElementById('totalAmount').innerText = finalTotal.toFixed(2);
            if (paymentType === 'credit') {
                document.getElementById('remainingBox').style.display = 'block';
                document.getElementById('remainingAmount').innerText = remainingAmount.toFixed(2);
            } else {
                document.getElementById('remainingBox').style.display = 'none';
            }

            document.getElementById('itemsData').value = JSON.stringify(items);
        }

        function togglePriceType() {
            priceType = priceType === 'retail' ? 'wholesale' : 'retail';
            document.getElementById('priceTypeBtn').innerText = priceType === 'retail' ? 'سعر القطاعي' : 'سعر الجملة';
            items.forEach(item => {
                const option = Array.from(document.getElementById('itemSelect').options).find(opt => opt.value === item.id);
                item.price = priceType === 'retail' ? parseFloat(option?.getAttribute('data-retail-price') ?? '0') || 0 : parseFloat(option?.getAttribute('data-wholesale-price') ?? '0') || 0;
                item.total = item.quantity * item.price;
            });
            updateTable();
            saveItemsToSession();
            const barcodeInput = document.getElementById('barcodeInput');
            if (barcodeInput && (!document.activeElement || document.activeElement === document.body)) {
                barcodeInput.focus();
            }
        }

        function togglePaidAmount() {
            const paymentType = document.getElementById('paymentType').value || 'cash';
            const paidAmountField = document.getElementById('paidAmountField');
            if (paymentType === 'credit') {
                paidAmountField.style.display = 'block';
            } else {
                paidAmountField.style.display = 'none';
                document.getElementById('remainingBox').style.display = 'none';
            }
            updateTotal();
            const barcodeInput = document.getElementById('barcodeInput');
            if (barcodeInput && (!document.activeElement || document.activeElement === document.body)) {
                barcodeInput.focus();
            }
        }

        function updateTotal() {
            updateTable();
        }

        function saveItemsToSession() {
            fetch('save_session.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'items_data=' + encodeURIComponent(JSON.stringify(items))
            })
            .then(response => response.text())
            .then(data => console.log(data))
            .catch(error => console.error('Error saving items to session:', error));
        }

        function submitForm(event) {
            event.preventDefault();
            const form = document.getElementById('invoiceForm');
            const formData = new FormData(form);
            const action = event.target.id === 'saveInvoiceBtn' ? 'save_invoice' : 'suspend';
            formData.append(action, '1');

            fetch('sales_invoice.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                console.log('Server response:', data);
                if (data.status === 'success') {
                    if (action === 'save_invoice') {
                        const invoiceId = data.invoice_id;
                        const invoiceNumber = data.invoice_number;
                        const itemsData = JSON.parse(document.getElementById('itemsData').value || '[]');
                        const total = itemsData.reduce((sum, item) => sum + (item.quantity * item.price), 0);
                        const discount = parseFloat(document.getElementById('discountValue').value) || 0;
                        const finalTotal = total - (document.getElementById('discountType').value === 'percentage' ? (total * discount / 100) : discount);
                        const paymentType = document.getElementById('paymentType').value || 'cash';
                        const clientName = document.getElementById('clientSelect').options[document.getElementById('clientSelect').selectedIndex].text;
                        const date = document.querySelector('input[name="date"]').value;
                        const userName = '<?php echo htmlspecialchars($user_name); ?>';

                        openPaymentWindow(finalTotal, invoiceId, itemsData, total, discount, finalTotal, paymentType, clientName, invoiceNumber, date, userName);
                    } else {
                        alert(data.message);
                        resetForm();
                    }
                } else {
                    alert('حدث خطأ: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error submitting form:', error);
                alert('حدث خطأ أثناء معالجة الطلب: ' + error.message);
            });
        }

        function openPaymentWindow(totalAmount, invoiceId, itemsData, subtotal, discount, finalTotal, paymentType, clientName, invoiceNumber, date, userName) {
            const paymentWindow = document.createElement('div');
            paymentWindow.className = 'payment-window';
            
            paymentWindow.innerHTML = `
                <div class="payment-container">
                    <h3>إتمام الدفع</h3>
                    <div class="payment-input-group">
                        <label>المبلغ الإجمالي</label>
                        <input type="number" id="totalAmountInput" value="${totalAmount.toFixed(2)}" readonly>
                    </div>
                    <div class="payment-input-group">
                        <label>المبلغ المدفوع</label>
                        <input type="number" id="paidAmountInput" value="${paymentType === 'cash' ? totalAmount.toFixed(2) : '0.00'}" step="0.01" autofocus>
                    </div>
                    <div class="payment-input-group">
                        <label>الباقي</label>
                        <input type="number" id="remainingAmountInput" value="0.00" readonly>
                    </div>
                    <div class="payment-buttons">
                        <button id="printInvoiceBtn">طباعة (Enter)</button>
                        <button id="cancelPaymentBtn">إلغاء (Esc)</button>
                    </div>
                </div>
            `;
            
            document.body.appendChild(paymentWindow);
            
            const paidAmountInput = document.getElementById('paidAmountInput');
            paidAmountInput.focus();
            paidAmountInput.select();
            
            paidAmountInput.addEventListener('input', function() {
                const paid = parseFloat(this.value) || 0;
                const remaining = totalAmount - paid;
                document.getElementById('remainingAmountInput').value = remaining.toFixed(2);
            });
            
            paidAmountInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    document.getElementById('printInvoiceBtn').click();
                }
            });
            
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape') {
                    paymentWindow.remove();
                }
            });
            
            document.getElementById('printInvoiceBtn').addEventListener('click', function() {
                const paidAmount = parseFloat(document.getElementById('paidAmountInput').value) || 0;
                const remainingAmount = parseFloat(document.getElementById('remainingAmountInput').value) || 0;
                
                printInvoice(invoiceId, itemsData, subtotal, discount, finalTotal, paidAmount, remainingAmount, paymentType, clientName, invoiceNumber, date, userName);
                
                paymentWindow.remove();
                resetForm();
            });
            
            document.getElementById('cancelPaymentBtn').addEventListener('click', function() {
                paymentWindow.remove();
            });
        }

        function resetForm() {
            items = [];
            document.getElementById('invoiceForm').reset();
            document.getElementById('itemsData').value = '';
            document.getElementById('totalAmount').innerText = '0.00';
            document.getElementById('remainingBox').style.display = 'none';
            updateTable();
            fetch('get_next_invoice_number.php')
                .then(response => response.json())
                .then(data => {
                    if (data.invoice_number) {
                        document.querySelector('input[name="invoice_number"]').value = data.invoice_number;
                    }
                })
                .catch(error => console.error('Error fetching next invoice number:', error));
            const barcodeInput = document.getElementById('barcodeInput');
            if (barcodeInput && (!document.activeElement || document.activeElement === document.body)) {
                barcodeInput.focus();
            }
        }

        function handleShortcuts(event) {
            switch (event.key) {
                case 'F5':
                    event.preventDefault();
                    document.getElementById('saveInvoiceBtn').click();
                    break;
                case 'F9':
                    event.preventDefault();
                    document.getElementById('suspendInvoiceBtn').click();
                    break;
                case 'F8':
                    event.preventDefault();
                    editQuantity();
                    break;
                case 'F10':
                    event.preventDefault();
                    toggleSidebar();
                    break;
            }
        }

        function editQuantity() {
            if (items.length === 0) {
                alert('لا توجد أصناف لتعديل الكمية.');
                return;
            }

            let itemList = items.map((item, index) => `${index + 1}. ${item.name} (الكمية: ${item.quantity})`).join('\n');
            let itemIndex = prompt(`اختر رقم الصنف لتعديل الكمية:\n${itemList}`);
            if (itemIndex && !isNaN(itemIndex) && itemIndex > 0 && itemIndex <= items.length) {
                itemIndex = parseInt(itemIndex) - 1;
                let newQuantity = prompt(`أدخل الكمية الجديدة لـ ${items[itemIndex].name}:`, items[itemIndex].quantity);
                if (newQuantity && !isNaN(newQuantity) && newQuantity > 0) {
                    updateQuantity(itemIndex, parseInt(newQuantity));
                } else {
                    alert('الكمية يجب أن تكون رقمًا موجبًا.');
                }
            } else {
                alert('رقم الصنف غير صالح.');
            }
            const barcodeInput = document.getElementById('barcodeInput');
            if (barcodeInput && (!document.activeElement || document.activeElement === document.body)) {
                barcodeInput.focus();
            }
        }

        function printInvoice(invoiceId, itemsData, total, discount, finalTotal, paidAmount, remainingAmount, paymentType, clientName, invoiceNumber, date, userName) {
            if (!itemsData || !Array.isArray(itemsData) || itemsData.length === 0) {
                console.error('No items data available for printing.');
                alert('لا يوجد بيانات أصناف للطباعة.');
                return;
            }

            const printWindow = window.open('', 'PRINT', 'height=400,width=300');
            if (!printWindow) {
                console.error('Failed to open print window. It might be blocked by the browser.');
                alert('فشل فتح نافذة الطباعة. قد تكون محظورة بواسطة المتصفح.');
                return;
            }

            const storeName = '<?php echo htmlspecialchars($store_settings['store_name'] ?? 'Astra'); ?>';
            const storePhone = '<?php echo htmlspecialchars($store_settings['phone'] ?? ''); ?>';
            const storeAddress = '<?php echo htmlspecialchars($store_settings['address'] ?? ''); ?>';
            const storeLogo = '<?php echo !empty($store_settings['logo']) ? "uploads/" . htmlspecialchars($store_settings['logo']) : ''; ?>';

            printWindow.document.write(`
                <html dir="rtl">
                <head>
                    <title>فاتورة بيع #${invoiceNumber}</title>
                    <style>
                        @media print {
                            body {
                                margin: 0;
                                padding: 0;
                                width: 80mm;
                                font-family: 'Arial', sans-serif;
                                font-size: 12px;
                                text-align: center;
                                direction: rtl;
                                line-height: 1.2;
                            }
                            table {
                                width: 100%;
                                border-collapse: collapse;
                            }
                            th, td {
    padding: 3px;
    border-bottom: 1px dashed #000;
    font-size: 11px;
    text-align: center;
    vertical-align: middle;
    white-space: nowrap;
}
                            .header, .footer {
                                margin: 3px 0;
                            }
                            h3 {
                                font-size: 14px;
                                margin: 5px 0;
                            }
                            p {
                                margin: 2px 0;
                            }
                            .logo {
                                width: 30mm;
                                height: 30mm;
                                margin: 5px auto;
                                display: block;
                            }
                            @page {
                                margin: 0;
                            }
                        }
                    </style>
                </head>
                <body>
                    <div class="header">
                        ${storeLogo ? `<img src="${storeLogo}" alt="Logo" class="logo">` : ''}
                        <h3>${storeName}</h3>
                        <h3>فاتورة بيع</h3>
                        <p>رقم الفاتورة: ${invoiceNumber}</p>
                        <p>التاريخ: ${date}</p>
                        <p>العميل: ${clientName}</p>
                        <p>المستخدم: ${userName}</p>
                    </div>
                    <table dir="rtl">
                        <thead>
                            <tr>
    <th style="width:20%">الصنف</th>
    <th style="width:5%">الكمية</th>
    <th style="width:20%">السعر</th>
    <th style="width:25%">الإجمالي</th>
</tr>
                        </thead>
                        <tbody>
                            ${itemsData.map(item => `
                                <tr>
                                    <td>${item.name || ''}</td>
                                    <td>${item.quantity || 0}</td>
                                    <td>${(item.price || 0).toFixed(2)}</td>
                                    <td>${(item.total || 0).toFixed(2)}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                    <div class="footer" dir="rtl">
                        <p>الإجمالي: ${total.toFixed(2)} ج.م</p>
                        <p>الخصم: ${discount.toFixed(2)} ج.م</p>
                        <p>الصافي: ${finalTotal.toFixed(2)} ج.م</p>
                        ${paymentType === 'credit' ? `
                            <p>المدفوع: ${paidAmount.toFixed(2)} ج.م</p>
                            <p>المتبقي: ${remainingAmount.toFixed(2)} ج.م</p>
                        ` : ''}
                        <p>نوع الدفع: ${paymentType === 'cash' ? 'نقدي' : 'آجل'}</p>
                        ${storePhone ? `<p>رقم الهاتف: ${storePhone}</p>` : ''}
                        ${storeAddress ? `<p>العنوان: ${storeAddress}</p>` : ''}
                    </div>
                </body>
                </html>
            `);

            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
            setTimeout(() => {
                if (!printWindow.closed) {
                    printWindow.close();
                }
            }, 1000);
        }

        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            const toggleBtn = document.getElementById('toggleSidebarBtn');
            const mainContent = document.querySelector('.main-content');

            isSidebarVisible = !isSidebarVisible;
            if (isSidebarVisible) {
                sidebar.classList.remove('hidden');
                toggleBtn.innerHTML = '<i class="fas fa-eye-slash"></i> إخفاء اللوحة';
                mainContent.classList.remove('full-width');
            } else {
                sidebar.classList.add('hidden');
                toggleBtn.innerHTML = '<i class="fas fa-eye"></i> إظهار اللوحة';
                mainContent.classList.add('full-width');
            }
        }

        function fetchItems(categoryId, button) {
            if (activeCategoryButton) {
                activeCategoryButton.classList.remove('active');
                const prevContainer = document.getElementById(`itemsContainer_${activeCategoryButton.dataset.categoryId}`);
                if (prevContainer) {
                    prevContainer.classList.remove('active');
                }
            }
            button.classList.add('active');
            activeCategoryButton = button;
            button.dataset.categoryId = categoryId;

            const itemsContainer = document.getElementById(`itemsContainer_${categoryId}`);
            if (itemsContainer) {
                itemsContainer.classList.add('active');
            }

            fetch('fetch_items.php?category_id=' + categoryId)
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success' && data.items.length > 0) {
                        itemsContainer.innerHTML = '<h4>الأصناف</h4>';
                        data.items.forEach(item => {
                            const button = document.createElement('button');
                            button.className = 'item-btn';
                            button.innerText = item.name;
                            button.onclick = () => addItem(item.id);
                            itemsContainer.appendChild(button);
                        });
                    } else {
                        itemsContainer.innerHTML = '<h4>الأصناف</h4><p style="color: #E74C3C;">لا توجد أصناف في هذا التصنيف.</p>';
                    }
                })
                .catch(error => {
                    console.error('Error fetching items:', error);
                    itemsContainer.innerHTML = '<h4>الأصناف</h4><p style="color: #E74C3C;">حدث خطأ أثناء جلب الأصناف.</p>';
                });
        }
    </script>
</body>
</html>