<?php
session_start();

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

require_once 'db_connect.php';

// جلب قائمة الموردين من قاعدة البيانات
$suppliers = $conn->query("SELECT id, name FROM suppliers ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

// معالجة طلب إنشاء التقرير
$report_data = [];
$total_invoice = 0;
$total_discount = 0;
$total_net = 0;
$total_paid = 0;
$total_remaining = 0;

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['generate_report'])) {
    $supplier_id = $_POST['supplier_id'];
    $date_from = $_POST['date_from'];
    $date_to = $_POST['date_to'];

    // التحقق من وجود سجلات في purchase_invoices
    $check_invoices = $conn->query("SELECT COUNT(*) FROM purchase_invoices")->fetchColumn();

    if ($check_invoices > 0) {
        // استعلام عادي إذا كانت هناك فواتير
        $query = "SELECT pi.invoice_number, s.name AS supplier_name, pi.date, i.name AS item_name, pii.quantity, pii.price, (pii.quantity * pii.price) AS item_total, pi.total AS invoice_total, 0 AS discount, pi.total AS net_total, pi.paid_amount AS paid, pi.remaining_amount AS remaining, pi.payment_type, 'شراء' AS record_type 
                  FROM purchase_invoices pi 
                  JOIN suppliers s ON pi.supplier_id = s.id 
                  JOIN purchase_invoice_items pii ON pi.id = pii.invoice_id 
                  JOIN items i ON pii.item_id = i.id 
                  WHERE 1=1";
        $params = [];

        if ($supplier_id !== 'all') {
            $query .= " AND pi.supplier_id = :supplier_id";
            $params[':supplier_id'] = $supplier_id;
        }
        if (!empty($date_from)) {
            $query .= " AND pi.date >= :date_from";
            $params[':date_from'] = $date_from;
        }
        if (!empty($date_to)) {
            $query .= " AND pi.date <= :date_to";
            $params[':date_to'] = $date_to;
        }

        $query .= " ORDER BY pi.date DESC";

        try {
            $stmt = $conn->prepare($query);
            $stmt->execute($params);
            $report_data = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // حساب الإجماليات
            foreach ($report_data as $row) {
                $total_invoice += (float)$row['invoice_total'];
                $total_discount += (float)$row['discount'];
                $total_net += (float)$row['net_total'];
                $total_paid += (float)$row['paid'];
                $total_remaining += (float)$row['remaining'];
            }
        } catch (PDOException $e) {
            $error_message = "خطأ في جلب البيانات: " . $e->getMessage();
        }
    } else {
        // إذا كان purchase_invoices فارغًا، جلب بيانات الموردين فقط
        $query = "SELECT s.name AS supplier_name, s.previous_debt AS remaining, 'لا توجد فواتير' AS record_type 
                  FROM suppliers s 
                  WHERE 1=1";
        $params = [];

        if ($supplier_id !== 'all') {
            $query .= " AND s.id = :supplier_id";
            $params[':supplier_id'] = $supplier_id;
        }

        $query .= " ORDER BY s.name";

        try {
            $stmt = $conn->prepare($query);
            $stmt->execute($params);
            $report_data = $stmt->fetchAll(PDO::FETCH_ASSOC);

            foreach ($report_data as $row) {
                $total_remaining += (float)$row['remaining'];
            }
        } catch (PDOException $e) {
            $error_message = "خطأ في جلب بيانات الموردين: " . $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, #E74C3C, #3498DB, #2ECC71);
            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: 40px;
            height: 100vh;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .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: #E74C3C;
            font-weight: bold;
            text-align: center;
            margin-bottom: 30px;
            text-shadow: 0 0 5px rgba(231, 76, 60, 0.5);
        }

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

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

        .form-control, .form-select {
            border-radius: 15px;
            border: 2px solid #E74C3C;
            padding: 8px 12px;
            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: #2ECC71;
            box-shadow: 0 0 10px rgba(46, 204, 113, 0.5), inset 0 2px 5px rgba(0, 0, 0, 0.1);
            background: #fff;
        }

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

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

        .btn-generate: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-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 i {
            margin-left: 8px;
        }

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

        .error-message {
            color: #E74C3C;
            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: #E74C3C;
            color: #fff;
        }

        .table tbody tr:hover {
            background: rgba(231, 76, 60, 0.1);
        }

        .totals-box {
            background: linear-gradient(45deg, #F1C40F, #D4AC0D);
            color: #fff;
            padding: 15px;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(241, 196, 15, 0.5);
            text-align: center;
            font-weight: bold;
            margin-top: 20px;
        }

        .table-responsive {
            max-height: 50vh;
            overflow-y: auto;
        }

        /* أنماط الطباعة */
        @media print {
            body * {
                visibility: hidden;
            }

            #printArea, #printArea * {
                visibility: visible !important;
                display: block !important;
            }

            #printArea {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                margin: 0;
                padding: 5mm;
                font-size: 8pt;
                line-height: 1.2;
                background: #fff;
                color: #333;
            }

            #printArea .report-header {
                text-align: center;
                margin-bottom: 5mm;
                border-bottom: 1px solid #E74C3C;
                padding-bottom: 3mm;
            }

            #printArea .report-header h1 {
                font-size: 12pt;
                color: #E74C3C;
                margin: 0;
            }

            #printArea .report-header p {
                font-size: 9pt;
                color: #333;
                margin: 2mm 0;
            }

            #printArea table {
                width: 100%;
                border-collapse: collapse;
                margin-bottom: 5mm;
                table-layout: fixed;
                page-break-inside: avoid;
            }

            #printArea table th, #printArea table td {
                border: 1px solid #333;
                padding: 2px;
                text-align: center;
                font-size: 8pt;
                color: #333;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }

            #printArea table th {
                background: #E74C3C;
                color: #fff;
                font-weight: bold;
            }

            #printArea table td {
                background: #fff;
            }

            #printArea table th:nth-child(1), #printArea table td:nth-child(1) { width: 20%; } /* اسم المورد أو رقم الفاتورة */
            #printArea table th:nth-child(2), #printArea table td:nth-child(2) { width: 20%; } /* الدين السابق أو اسم المورد */
            #printArea table th:nth-child(3), #printArea table td:nth-child(3) { width: 20%; } /* نوع السجل أو التاريخ */
            #printArea table th:nth-child(4), #printArea table td:nth-child(4) { width: 10%; } /* اسم الصنف */
            #printArea table th:nth-child(5), #printArea table td:nth-child(5) { width: 6%; } /* الكمية */
            #printArea table th:nth-child(6), #printArea table td:nth-child(6) { width: 6%; } /* السعر */
            #printArea table th:nth-child(7), #printArea table td:nth-child(7) { width: 8%; } /* إجمالي الصنف */
            #printArea table th:nth-child(8), #printArea table td:nth-child(8) { width: 8%; } /* إجمالي الفاتورة */
            #printArea table th:nth-child(9), #printArea table td:nth-child(9) { width: 6%; } /* الخصم */
            #printArea table th:nth-child(10), #printArea table td:nth-child(10) { width: 6%; } /* الصافي */
            #printArea table th:nth-child(11), #printArea table td:nth-child(11) { width: 6%; } /* المدفوع */
            #printArea table th:nth-child(12), #printArea table td:nth-child(12) { width: 6%; } /* المتبقي */
            #printArea table th:nth-child(13), #printArea table td:nth-child(13) { width: 6%; } /* نوع الدفع */
            #printArea table th:nth-child(14), #printArea table td:nth-child(14) { width: 6%; } /* نوع السجل */

            #printArea .totals {
                text-align: left;
                font-size: 9pt;
                font-weight: bold;
                margin-top: 3mm;
                padding: 3mm;
                border-top: 1px solid #E74C3C;
            }

            #printArea .totals p {
                margin: 2mm 0;
            }

            @page {
                size: A4 landscape;
                margin: 5mm;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="card">
            <h2><i class="fas fa-file-alt me-2"></i> تقارير الموردين</h2>
            <?php if (isset($error_message)): ?>
                <div class="error-message"><?php echo $error_message; ?></div>
            <?php endif; ?>
            <form method="POST">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label"><i class="fas fa-truck"></i> المورد</label>
                        <select class="form-select" name="supplier_id">
                            <option value="all">جميع الموردين</option>
                            <?php foreach ($suppliers as $supplier): ?>
                                <option value="<?php echo htmlspecialchars($supplier['id']); ?>">
                                    <?php echo htmlspecialchars($supplier['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label"><i class="fas fa-calendar-alt"></i> من تاريخ</label>
                        <input type="date" class="form-control" name="date_from" value="<?php echo isset($_POST['date_from']) ? htmlspecialchars($_POST['date_from']) : ''; ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label"><i class="fas fa-calendar-alt"></i> إلى تاريخ</label>
                        <input type="date" class="form-control" name="date_to" value="<?php echo isset($_POST['date_to']) ? htmlspecialchars($_POST['date_to']) : ''; ?>">
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-generate mt-4" name="generate_report"><i class="fas fa-search"></i> إنشاء التقرير</button>
                    </div>
                    <div class="col-md-2">
                        <button type="button" class="btn btn-cancel mt-4" onclick="window.location.href='dashboard.php'"><i class="fas fa-times"></i> إلغاء</button>
                    </div>
                </div>
            </form>
        </div>

        <?php if (!empty($report_data)): ?>
            <div class="card">
                <h2><i class="fas fa-table me-2"></i> نتائج التقرير</h2>
                <div class="table-responsive">
                    <table class="table table-striped" id="reportTable">
                        <thead>
                            <?php if (isset($report_data[0]['invoice_number'])): ?>
                                <tr>
                                    <th>رقم الفاتورة</th>
                                    <th>اسم المورد</th>
                                    <th>التاريخ</th>
                                    <th>اسم الصنف</th>
                                    <th>الكمية</th>
                                    <th>السعر</th>
                                    <th>إجمالي الصنف</th>
                                    <th>إجمالي الفاتورة</th>
                                    <th>الخصم</th>
                                    <th>الصافي</th>
                                    <th>المدفوع</th>
                                    <th>المتبقي</th>
                                    <th>نوع الدفع</th>
                                    <th>نوع السجل</th>
                                </tr>
                            <?php else: ?>
                                <tr>
                                    <th>اسم المورد</th>
                                    <th>الدين السابق</th>
                                    <th>نوع السجل</th>
                                </tr>
                            <?php endif; ?>
                        </thead>
                        <tbody>
                            <?php foreach ($report_data as $row): ?>
                                <tr>
                                    <?php if (isset($row['invoice_number'])): ?>
                                        <td><?php echo htmlspecialchars($row['invoice_number']); ?></td>
                                        <td><?php echo htmlspecialchars($row['supplier_name']); ?></td>
                                        <td><?php echo htmlspecialchars($row['date']); ?></td>
                                        <td><?php echo htmlspecialchars($row['item_name']); ?></td>
                                        <td><?php echo htmlspecialchars($row['quantity']); ?></td>
                                        <td><?php echo number_format($row['price'], 2); ?></td>
                                        <td><?php echo number_format($row['item_total'], 2); ?></td>
                                        <td><?php echo number_format($row['invoice_total'], 2); ?></td>
                                        <td><?php echo number_format($row['discount'], 2); ?></td>
                                        <td><?php echo number_format($row['net_total'], 2); ?></td>
                                        <td><?php echo number_format($row['paid'], 2); ?></td>
                                        <td><?php echo number_format($row['remaining'], 2); ?></td>
                                        <td><?php echo htmlspecialchars($row['payment_type']); ?></td>
                                        <td><?php echo htmlspecialchars($row['record_type']); ?></td>
                                    <?php else: ?>
                                        <td><?php echo htmlspecialchars($row['supplier_name']); ?></td>
                                        <td><?php echo number_format($row['remaining'], 2); ?></td>
                                        <td><?php echo htmlspecialchars($row['record_type']); ?></td>
                                    <?php endif; ?>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <div class="totals-box">
                    <?php if (isset($report_data[0]['invoice_number'])): ?>
                        <p>إجمالي الفواتير: <?php echo number_format($total_invoice, 2); ?> ج.م</p>
                        <p>إجمالي الخصم: <?php echo number_format($total_discount, 2); ?> ج.م</p>
                        <p>الصافي: <?php echo number_format($total_net, 2); ?> ج.م</p>
                        <p>المدفوع: <?php echo number_format($total_paid, 2); ?> ج.م</p>
                        <p>المتبقي: <?php echo number_format($total_remaining, 2); ?> ج.م</p>
                    <?php else: ?>
                        <p>إجمالي الدين السابق: <?php echo number_format($total_remaining, 2); ?> ج.م</p>
                    <?php endif; ?>
                </div>
                <button type="button" class="btn btn-print mt-3" onclick="printReport()"><i class="fas fa-print"></i> طباعة التقرير</button>
            </div>

            <!-- منطقة الطباعة -->
            <div id="printArea" style="display: none;">
                <div class="report-header">
                    <h1>تقرير الموردين</h1>
                    <p>من تاريخ: <?php echo isset($_POST['date_from']) ? htmlspecialchars($_POST['date_from']) : 'غير محدد'; ?> 
                       إلى تاريخ: <?php echo isset($_POST['date_to']) ? htmlspecialchars($_POST['date_to']) : 'غير محدد'; ?></p>
                    <p>المورد: <?php echo $_POST['supplier_id'] === 'all' ? 'جميع الموردين' : htmlspecialchars($suppliers[array_search($_POST['supplier_id'], array_column($suppliers, 'id'))]['name']); ?></p>
                </div>
                <table>
                    <thead>
                        <?php if (isset($report_data[0]['invoice_number'])): ?>
                            <tr>
                                <th>رقم الفاتورة</th>
                                <th>اسم المورد</th>
                                <th>التاريخ</th>
                                <th>اسم الصنف</th>
                                <th>الكمية</th>
                                <th>السعر</th>
                                <th>إجمالي الصنف</th>
                                <th>إجمالي الفاتورة</th>
                                <th>الخصم</th>
                                <th>الصافي</th>
                                <th>المدفوع</th>
                                <th>المتبقي</th>
                                <th>نوع الدفع</th>
                                <th>نوع السجل</th>
                            </tr>
                        <?php else: ?>
                            <tr>
                                <th>اسم المورد</th>
                                <th>الدين السابق</th>
                                <th>نوع السجل</th>
                            </tr>
                        <?php endif; ?>
                    </thead>
                    <tbody>
                        <?php foreach ($report_data as $row): ?>
                            <tr>
                                <?php if (isset($row['invoice_number'])): ?>
                                    <td><?php echo htmlspecialchars($row['invoice_number']); ?></td>
                                    <td><?php echo htmlspecialchars($row['supplier_name']); ?></td>
                                    <td><?php echo htmlspecialchars($row['date']); ?></td>
                                    <td><?php echo htmlspecialchars($row['item_name']); ?></td>
                                    <td><?php echo htmlspecialchars($row['quantity']); ?></td>
                                    <td><?php echo number_format($row['price'], 2); ?></td>
                                    <td><?php echo number_format($row['item_total'], 2); ?></td>
                                    <td><?php echo number_format($row['invoice_total'], 2); ?></td>
                                    <td><?php echo number_format($row['discount'], 2); ?></td>
                                    <td><?php echo number_format($row['net_total'], 2); ?></td>
                                    <td><?php echo number_format($row['paid'], 2); ?></td>
                                    <td><?php echo number_format($row['remaining'], 2); ?></td>
                                    <td><?php echo htmlspecialchars($row['payment_type']); ?></td>
                                    <td><?php echo htmlspecialchars($row['record_type']); ?></td>
                                <?php else: ?>
                                    <td><?php echo htmlspecialchars($row['supplier_name']); ?></td>
                                    <td><?php echo number_format($row['remaining'], 2); ?></td>
                                    <td><?php echo htmlspecialchars($row['record_type']); ?></td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <div class="totals">
                    <?php if (isset($report_data[0]['invoice_number'])): ?>
                        <p>إجمالي الفواتير: <?php echo number_format($total_invoice, 2); ?> ج.م</p>
                        <p>إجمالي الخصم: <?php echo number_format($total_discount, 2); ?> ج.م</p>
                        <p>الصافي: <?php echo number_format($total_net, 2); ?> ج.م</p>
                        <p>المدفوع: <?php echo number_format($total_paid, 2); ?> ج.م</p>
                        <p>المتبقي: <?php echo number_format($total_remaining, 2); ?> ج.م</p>
                    <?php else: ?>
                        <p>إجمالي الدين السابق: <?php echo number_format($total_remaining, 2); ?> ج.م</p>
                    <?php endif; ?>
                </div>
            </div>
        <?php elseif ($_SERVER["REQUEST_METHOD"] == "POST"): ?>
            <div class="error-message">لا توجد بيانات للعرض بناءً على المعايير المحددة!</div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function printReport() {
            const printTable = document.querySelector('#printArea table tbody');
            if (printTable && printTable.children.length === 0) {
                alert('لا توجد بيانات للطباعة!');
                return;
            }

            setTimeout(() => {
                window.print();
            }, 100);
        }
    </script>
</body>
</html>