<?php
session_start();

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

require_once 'db_connect.php';

// جلب اسم المستخدم الحالي
$user_name = $_SESSION['user_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' => 'عميل افتراضي'];
}

// معالجة البيانات عند إرسال النموذج
$invoices = [];
$total_debt = 0;
$selected_client_id = '';
$start_date = '';
$end_date = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $selected_client_id = $_POST['client_id'] ?? '';
    $start_date = $_POST['start_date'] ?? '';
    $end_date = $_POST['end_date'] ?? '';

    // تحقق من صحة التواريخ
    if (!empty($start_date) && !empty($end_date)) {
        try {
            $query = "SELECT si.*, c.name as client_name 
                     FROM sales_invoices si 
                     JOIN clients c ON si.client_id = c.id 
                     WHERE si.payment_type = 'credit' 
                     AND si.date BETWEEN :start_date AND :end_date";
            
            // إذا لم يتم اختيار "كل العملاء"، أضف شرط العميل
            if ($selected_client_id !== 'all') {
                $query .= " AND si.client_id = :client_id";
            }

            $stmt = $conn->prepare($query);
            $stmt->bindValue(':start_date', $start_date);
            $stmt->bindValue(':end_date', $end_date);
            if ($selected_client_id !== 'all') {
                $stmt->bindValue(':client_id', $selected_client_id, PDO::PARAM_INT);
            }
            $stmt->execute();
            $invoices = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // حساب إجمالي المديونيات
            foreach ($invoices as $invoice) {
                $total_debt += $invoice['remaining_amount'];
            }
        } catch (PDOException $e) {
            error_log("Error fetching invoices: " . $e->getMessage());
            $invoices = [];
        }
    }
}
?>

<!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, .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;
        }

        .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, #2ECC71, #27AE60);
            border: none;
            color: #fff;
        }

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

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

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

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

        .btn-back:hover {
            background: linear-gradient(45deg, #C0392B, #A93226);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(231, 76, 60, 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);
        }

        .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.2rem;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="card">
            <h2><i class="fas fa-file-invoice-dollar me-2"></i> كشف حساب العميل</h2>
            <form method="POST" id="statementForm">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label"><i class="fas fa-user"></i> العميل</label>
                        <select class="form-select" name="client_id" required>
                            <option value="all">كل العملاء</option>
                            <?php foreach ($clients as $client): ?>
                                <option value="<?php echo $client['id']; ?>" <?php echo $selected_client_id == $client['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($client['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label"><i class="fas fa-calendar"></i> من تاريخ</label>
                        <input type="date" class="form-control" name="start_date" value="<?php echo $start_date; ?>" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label"><i class="fas fa-calendar"></i> إلى تاريخ</label>
                        <input type="date" class="form-control" name="end_date" value="<?php echo $end_date; ?>" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">&nbsp;</label>
                        <button type="submit" class="btn btn-search w-100"><i class="fas fa-search"></i> بحث</button>
                    </div>
                </div>
            </form>

            <?php if (!empty($invoices)): ?>
                <div class="table-responsive" style="max-height: 50vh; overflow-y: auto; margin-top: 20px;">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>رقم الفاتورة</th>
                                <th>اسم العميل</th>
                                <th>التاريخ</th>
                                <th>الإجمالي</th>
                                <th>المدفوع</th>
                                <th>المتبقي</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($invoices as $invoice): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($invoice['invoice_number']); ?></td>
                                    <td><?php echo htmlspecialchars($invoice['client_name']); ?></td>
                                    <td><?php echo htmlspecialchars($invoice['date']); ?></td>
                                    <td><?php echo number_format($invoice['final_total'], 2); ?></td>
                                    <td><?php echo number_format($invoice['paid_amount'], 2); ?></td>
                                    <td><?php echo number_format($invoice['remaining_amount'], 2); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <div class="total-box">
                    إجمالي المديونيات: <span><?php echo number_format($total_debt, 2); ?></span> ج.م
                </div>
                <div class="text-center mt-3">
                    <button type="button" class="btn btn-print" onclick="printStatement()"><i class="fas fa-print"></i> طباعة التقرير</button>
                    <button type="button" class="btn btn-back" onclick="window.location.href='dashboard.php'"><i class="fas fa-arrow-right"></i> العودة</button>
                </div>
            <?php elseif ($_SERVER["REQUEST_METHOD"] == "POST"): ?>
                <p style="color: #E74C3C; text-align: center; margin-top: 20px;">لا توجد فواتير آجلة في الفترة المحددة.</p>
            <?php endif; ?>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function printStatement() {
            const invoices = <?php echo json_encode($invoices); ?>;
            const totalDebt = <?php echo json_encode($total_debt); ?>;
            const startDate = '<?php echo $start_date; ?>';
            const endDate = '<?php echo $end_date; ?>';
            const selectedClientId = '<?php echo $selected_client_id; ?>';
            const userName = '<?php echo htmlspecialchars($user_name); ?>';
            let clientName = selectedClientId === 'all' ? 'كل العملاء' : document.querySelector(`select[name="client_id"] option[value="${selectedClientId}"]`).text;

            const printWindow = window.open('', 'PRINT', 'height=400,width=300');
            printWindow.document.write(`
                <html dir="rtl">
                <head>
                    <title>كشف حساب العميل</title>
                    <style>
                        @media print {
                            body {
                                margin: 0;
                                padding: 5mm;
                                width: 80mm;
                                font-family: 'Arial', sans-serif;
                                font-size: 12px;
                                text-align: center;
                                direction: rtl;
                            }
                            table {
                                width: 100%;
                                border-collapse: collapse;
                            }
                            th, td {
                                padding: 5px;
                                border-bottom: 1px dashed #000;
                            }
                            .header, .footer {
                                margin: 5px 0;
                            }
                        }
                    </style>
                </head>
                <body>
                    <div class="header">
                        <h3>كشف حساب العميل</h3>
                        <p>العميل: ${clientName}</p>
                        <p>من تاريخ: ${startDate}</p>
                        <p>إلى تاريخ: ${endDate}</p>
                        <p>المستخدم: ${userName}</p>
                    </div>
                    <table dir="rtl">
                        <thead>
                            <tr>
                                <th>رقم الفاتورة</th>
                                <th>التاريخ</th>
                                <th>الإجمالي</th>
                                <th>المدفوع</th>
                                <th>المتبقي</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${invoices.map(invoice => `
                                <tr>
                                    <td>${invoice.invoice_number}</td>
                                    <td>${invoice.date}</td>
                                    <td>${Number(invoice.final_total).toFixed(2)}</td>
                                    <td>${Number(invoice.paid_amount).toFixed(2)}</td>
                                    <td>${Number(invoice.remaining_amount).toFixed(2)}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                    <div class="footer" dir="rtl">
                        <p>إجمالي المديونيات: ${Number(totalDebt).toFixed(2)} ج.م</p>
                    </div>
                </body>
                </html>
            `);

            printWindow.document.close();
            printWindow.focus();
            setTimeout(() => {
                printWindow.print();
                printWindow.close();
            }, 500);
        }
    </script>
</body>
</html>