<?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.");
}

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

// جلب الفواتير التي تم سدادها بالكامل
$completed_invoices = [];
try {
    $stmt = $conn->query("
        SELECT si.id, si.invoice_number, si.date, si.final_total, si.advance_payment, si.remaining_amount, si.installment_duration, c.id AS client_id, c.name AS client_name,
               GROUP_CONCAT(i.name) AS item_names
        FROM sales_invoices si
        JOIN clients c ON si.client_id = c.id
        JOIN sales_invoice_items sii ON sii.invoice_id = si.id
        JOIN items i ON sii.item_id = i.id
        WHERE si.installment_type = 'installment' AND si.remaining_amount = 0
        GROUP BY si.id
        ORDER BY si.date DESC
    ");
    $completed_invoices = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching completed installment invoices: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Astra - الأقساط المنتهية</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            min-height: 100vh;
            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, h4 {
            color: #2ECC71;
            font-weight: bold;
            text-align: center;
            margin-bottom: 20px;
            text-shadow: 0 0 5px rgba(46, 204, 113, 0.5);
        }

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

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

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

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

        .btn i {
            margin-left: 8px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="card">
            <h2><i class="fas fa-check-circle me-2"></i> الأقساط المنتهية</h2>

            <!-- جدول الفواتير التي تم سدادها بالكامل -->
            <h4>الفواتير المنتهية</h4>
            <div class="row mb-3">
                <div class="col-md-4">
                    <label class="form-label"><i class="fas fa-user"></i> فلتر حسب العميل</label>
                    <select class="form-select" id="clientFilter" onchange="filterInvoices()">
                        <option value="">جميع العملاء</option>
                        <?php
                        $clients = $conn->query("SELECT id, name FROM clients")->fetchAll(PDO::FETCH_ASSOC);
                        foreach ($clients as $client) {
                            echo '<option value="' . $client['id'] . '">' . htmlspecialchars($client['name']) . '</option>';
                        }
                        ?>
                    </select>
                </div>
            </div>
            <div class="table-responsive" style="max-height: 50vh; overflow-y: auto;">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>رقم الفاتورة</th>
                            <th>التاريخ</th>
                            <th>اسم العميل</th>
                            <th>الأصناف</th>
                            <th>الإجمالي</th>
                            <th>الدفعة المقدمة</th>
                            <th>المتبقي</th>
                            <th>مدة التقسيط</th>
                            <th>الإجراء</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($completed_invoices)): ?>
                            <?php foreach ($completed_invoices as $invoice): ?>
                                <tr data-client-id="<?php echo $invoice['client_id']; ?>">
                                    <td><?php echo htmlspecialchars($invoice['invoice_number']); ?></td>
                                    <td><?php echo htmlspecialchars($invoice['date']); ?></td>
                                    <td><?php echo htmlspecialchars($invoice['client_name']); ?></td>
                                    <td><?php echo htmlspecialchars($invoice['item_names']); ?></td>
                                    <td><?php echo number_format($invoice['final_total'], 2); ?> ج.م</td>
                                    <td><?php echo number_format($invoice['advance_payment'], 2); ?> ج.م</td>
                                    <td><?php echo number_format($invoice['remaining_amount'], 2); ?> ج.م</td>
                                    <td><?php echo htmlspecialchars($invoice['installment_duration']); ?> شهر</td>
                                    <td>
                                        <button class="btn btn-details" onclick="showInstallmentDetails(<?php echo $invoice['id']; ?>)">
                                            <i class="fas fa-eye"></i> عرض التفاصيل
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="9" style="text-align: center; color: #E74C3C;">لا توجد فواتير تقسيط منتهية.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- قسم تفاصيل الأقساط -->
            <div id="installmentDetails" style="display: none; margin-top: 20px;">
                <h4>تفاصيل الأقساط</h4>
                <div class="table-responsive" style="max-height: 30vh; overflow-y: auto;">
                    <table class="table table-striped" id="installmentsTable">
                        <thead>
                            <tr>
                                <th>رقم القسط</th>
                                <th>المبلغ</th>
                                <th>تاريخ الاستحقاق</th>
                                <th>الحالة</th>
                                <th>تاريخ الدفع</th>
                            </tr>
                        </thead>
                        <tbody id="installmentsTableBody">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function showInstallmentDetails(invoiceId) {
            fetch('fetch_installments.php?invoice_id=' + invoiceId)
                .then(response => response.json())
                .then(data => {
                    const tableBody = document.getElementById('installmentsTableBody');
                    tableBody.innerHTML = '';
                    if (data.status === 'success' && data.installments.length > 0) {
                        data.installments.forEach(installment => {
                            const row = document.createElement('tr');
                            row.innerHTML = `
                                <td>${installment.installment_number}</td>
                                <td>${Number(installment.amount).toFixed(2)} ج.م</td>
                                <td>${installment.due_date}</td>
                                <td>${installment.status === 'pending' ? 'معلق' : 'مدفوع'}</td>
                                <td>${installment.paid_date || '-'}</td>
                            `;
                            tableBody.appendChild(row);
                        });
                        document.getElementById('installmentDetails').style.display = 'block';
                    } else {
                        tableBody.innerHTML = '<tr><td colspan="5" style="text-align: center; color: #E74C3C;">لا توجد أقساط لهذه الفاتورة.</td></tr>';
                        document.getElementById('installmentDetails').style.display = 'block';
                    }
                })
                .catch(error => {
                    console.error('Error fetching installments:', error);
                    document.getElementById('installmentsTableBody').innerHTML = '<tr><td colspan="5" style="text-align: center; color: #E74C3C;">حدث خطأ أثناء جلب الأقساط.</td></tr>';
                    document.getElementById('installmentDetails').style.display = 'block';
                });
        }

        function filterInvoices() {
            const clientId = document.getElementById('clientFilter').value;
            const rows = document.querySelectorAll('table.table-striped tbody tr');
            rows.forEach(row => {
                const rowClientId = row.getAttribute('data-client-id');
                if (!clientId || rowClientId === clientId) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        }
    </script>
</body>
</html>