<?php
session_start();

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

require_once 'db_connect.php';

// جلب بيانات المحل من جدول settings
$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 = 'مستخدم غير محدد';
    }
}

// تحديد التاريخ المطلوب (افتراضيًا اليوم)
$selected_date = date('Y-m-d'); // التاريخ الحالي
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['selected_date'])) {
    $selected_date = $_POST['selected_date'];
}

// جلب بيانات المبيعات (نقدي وآجل)
$total_sales_cash = 0;
$total_sales_credit = 0;
try {
    $stmt = $conn->prepare("SELECT payment_type, SUM(final_total) as total FROM sales_invoices WHERE DATE(date) = :selected_date GROUP BY payment_type");
    $stmt->execute([':selected_date' => $selected_date]);
    $sales_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($sales_data as $sale) {
        if ($sale['payment_type'] == 'cash') {
            $total_sales_cash = $sale['total'] ?? 0;
        } elseif ($sale['payment_type'] == 'credit') {
            $total_sales_credit = $sale['total'] ?? 0;
        }
    }
} catch (PDOException $e) {
    error_log("Error fetching sales data: " . $e->getMessage());
}

// جلب بيانات المشتريات
$total_purchases = 0;
try {
    $stmt = $conn->prepare("SELECT SUM(total) as total FROM purchase_invoices WHERE DATE(date) = :selected_date");
    $stmt->execute([':selected_date' => $selected_date]);
    $total_purchases = $stmt->fetchColumn() ?: 0;
} catch (PDOException $e) {
    error_log("Error fetching purchases data: " . $e->getMessage());
}

// جلب بيانات مرتجعات البيع
$total_sales_returns = 0;
try {
    $stmt = $conn->prepare("SELECT SUM(amount) as total FROM sales_returns WHERE DATE(return_date) = :selected_date");
    $stmt->execute([':selected_date' => $selected_date]);
    $total_sales_returns = $stmt->fetchColumn() ?: 0;
} catch (PDOException $e) {
    error_log("Error fetching sales returns data: " . $e->getMessage());
}

// جلب بيانات مرتجعات الشراء
$total_purchase_returns = 0;
try {
    $stmt = $conn->prepare("SELECT SUM(amount) as total FROM purchase_returns WHERE DATE(return_date) = :selected_date");
    $stmt->execute([':selected_date' => $selected_date]);
    $total_purchase_returns = $stmt->fetchColumn() ?: 0;
} catch (PDOException $e) {
    error_log("Error fetching purchase returns data: " . $e->getMessage());
}

// جلب بيانات رواتب الموظفين
$total_salaries = 0;
try {
    $stmt = $conn->prepare("SELECT SUM(net_salary) as total FROM salary_payments WHERE DATE(payment_date) = :selected_date");
    $stmt->execute([':selected_date' => $selected_date]);
    $total_salaries = $stmt->fetchColumn() ?: 0;
} catch (PDOException $e) {
    error_log("Error fetching salaries data: " . $e->getMessage());
}

// جلب بيانات المصروفات
$total_expenses = 0;
try {
    $stmt = $conn->prepare("SELECT SUM(amount) as total FROM expenses WHERE DATE(date) = :selected_date");
    $stmt->execute([':selected_date' => $selected_date]);
    $total_expenses = $stmt->fetchColumn() ?: 0;
} catch (PDOException $e) {
    error_log("Error fetching expenses data: " . $e->getMessage());
}

// جلب بيانات معاملات الخزنة (إيداع وسحب)
$total_deposits = 0;
$total_withdrawals = 0;
try {
    $stmt = $conn->prepare("SELECT transaction_type, SUM(amount) as total FROM treasury_transactions WHERE DATE(date) = :selected_date GROUP BY transaction_type");
    $stmt->execute([':selected_date' => $selected_date]);
    $treasury_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($treasury_data as $transaction) {
        if ($transaction['transaction_type'] == 'income' || $transaction['transaction_type'] == 'deposit') {
            $total_deposits += $transaction['total'] ?? 0;
        } elseif ($transaction['transaction_type'] == 'withdrawal') {
            $total_withdrawals += $transaction['total'] ?? 0;
        }
    }
} catch (PDOException $e) {
    error_log("Error fetching treasury transactions: " . $e->getMessage());
}

// حساب الإجماليات
$total_sales = $total_sales_cash + $total_sales_credit;
?>

<!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;
            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: column;
        }

        .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 {
            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 {
            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;
        }

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

        .btn-search {
            background: linear-gradient(45deg, #3498DB, #2980B9);
            border: none;
            color: #fff;
        }

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

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

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

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

        .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);
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="card">
            <h2><i class="fas fa-chart-line me-2"></i> التقرير اليومي</h2>
            <form method="POST" id="searchForm">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label"><i class="fas fa-calendar"></i> اختر التاريخ</label>
                        <input type="date" class="form-control" name="selected_date" value="<?php echo $selected_date; ?>" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label"> </label>
                        <button type="submit" class="btn btn-search"><i class="fas fa-search"></i> بحث</button>
                        <button type="button" class="btn btn-print" onclick="printReport()"><i class="fas fa-print"></i> طباعة التقرير</button>
                    </div>
                </div>
            </form>

            <div class="table-responsive mt-4">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>البيان</th>
                            <th>القيمة (ج.م)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>إجمالي المبيعات النقدية</td>
                            <td><?php echo number_format($total_sales_cash, 2); ?></td>
                        </tr>
                        <tr>
                            <td>إجمالي المبيعات الآجلة</td>
                            <td><?php echo number_format($total_sales_credit, 2); ?></td>
                        </tr>
                        <tr>
                            <td>الإجمالي الكلي للمبيعات</td>
                            <td><?php echo number_format($total_sales, 2); ?></td>
                        </tr>
                        <tr>
                            <td>إجمالي المشتريات</td>
                            <td><?php echo number_format($total_purchases, 2); ?></td>
                        </tr>
                        <tr>
                            <td>إجمالي مرتجعات البيع</td>
                            <td><?php echo number_format($total_sales_returns, 2); ?></td>
                        </tr>
                        <tr>
                            <td>إجمالي مرتجعات الشراء</td>
                            <td><?php echo number_format($total_purchase_returns, 2); ?></td>
                        </tr>
                        <tr>
                            <td>إجمالي رواتب الموظفين</td>
                            <td><?php echo number_format($total_salaries, 2); ?></td>
                        </tr>
                        <tr>
                            <td>إجمالي المصروفات</td>
                            <td><?php echo number_format($total_expenses, 2); ?></td>
                        </tr>
                        <tr>
                            <td>إجمالي إيداعات الخزنة</td>
                            <td><?php echo number_format($total_deposits, 2); ?></td>
                        </tr>
                        <tr>
                            <td>إجمالي سحوبات الخزنة</td>
                            <td><?php echo number_format($total_withdrawals, 2); ?></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function printReport() {
            const selectedDate = '<?php echo $selected_date; ?>';
            const userName = '<?php echo htmlspecialchars($user_name); ?>';
            const totalSalesCash = '<?php echo number_format($total_sales_cash, 2); ?>';
            const totalSalesCredit = '<?php echo number_format($total_sales_credit, 2); ?>';
            const totalSales = '<?php echo number_format($total_sales, 2); ?>';
            const totalPurchases = '<?php echo number_format($total_purchases, 2); ?>';
            const totalSalesReturns = '<?php echo number_format($total_sales_returns, 2); ?>';
            const totalPurchaseReturns = '<?php echo number_format($total_purchase_returns, 2); ?>';
            const totalSalaries = '<?php echo number_format($total_salaries, 2); ?>';
            const totalExpenses = '<?php echo number_format($total_expenses, 2); ?>';
            const totalDeposits = '<?php echo number_format($total_deposits, 2); ?>';
            const totalWithdrawals = '<?php echo number_format($total_withdrawals, 2); ?>';

            // جلب بيانات المحل من PHP
            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']) : ''; ?>';

            // إنشاء نافذة الطباعة
            const printWindow = window.open('', 'PRINT', 'height=400,width=300');
            if (!printWindow) {
                alert('فشل فتح نافذة الطباعة. قد تكون محظورة بواسطة المتصفح.');
                return;
            }

            printWindow.document.write(`
                <html dir="rtl">
                <head>
                    <title>التقرير اليومي - ${selectedDate}</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: 2px;
                                border-bottom: 1px dashed #000;
                                font-size: 12px;
                            }
                            .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>التاريخ: ${selectedDate}</p>
                        <p>المستخدم: ${userName}</p>
                    </div>
                    <table dir="rtl">
                        <tbody>
                            <tr>
                                <td>إجمالي المبيعات النقدية</td>
                                <td>${totalSalesCash} ج.م</td>
                            </tr>
                            <tr>
                                <td>إجمالي المبيعات الآجلة</td>
                                <td>${totalSalesCredit} ج.م</td>
                            </tr>
                            <tr>
                                <td>الإجمالي الكلي للمبيعات</td>
                                <td>${totalSales} ج.م</td>
                            </tr>
                            <tr>
                                <td>إجمالي المشتريات</td>
                                <td>${totalPurchases} ج.م</td>
                            </tr>
                            <tr>
                                <td>إجمالي مرتجعات البيع</td>
                                <td>${totalSalesReturns} ج.م</td>
                            </tr>
                            <tr>
                                <td>إجمالي مرتجعات الشراء</td>
                                <td>${totalPurchaseReturns} ج.م</td>
                            </tr>
                            <tr>
                                <td>إجمالي رواتب الموظفين</td>
                                <td>${totalSalaries} ج.م</td>
                            </tr>
                            <tr>
                                <td>إجمالي المصروفات</td>
                                <td>${totalExpenses} ج.م</td>
                            </tr>
                            <tr>
                                <td>إجمالي إيداعات الخزنة</td>
                                <td>${totalDeposits} ج.م</td>
                            </tr>
                            <tr>
                                <td>إجمالي سحوبات الخزنة</td>
                                <td>${totalWithdrawals} ج.م</td>
                            </tr>
                        </tbody>
                    </table>
                    <div class="footer" dir="rtl">
                        ${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);
        }
    </script>
</body>
</html>