<?php
session_start();

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

require_once 'db_connect.php';

// متغيرات البحث
$search_invoice_id = isset($_GET['search_invoice_id']) ? intval($_GET['search_invoice_id']) : '';
$start_date = isset($_GET['start_date']) ? trim($_GET['start_date']) : '';
$end_date = isset($_GET['end_date']) ? trim($_GET['end_date']) : '';
$returns = [];

// جلب فواتير المرتجعات
try {
    $query = "SELECT sr.id, sr.invoice_id, sr.amount, sr.return_date, t.name AS treasury_name, c.name AS customer_name 
              FROM sales_returns sr 
              LEFT JOIN treasuries t ON sr.treasury_id = t.id 
              LEFT JOIN sales_invoices si ON sr.invoice_id = si.id 
              LEFT JOIN clients c ON si.client_id = c.id";
    
    $conditions = [];
    $params = [];

    if (!empty($search_invoice_id)) {
        $conditions[] = "sr.invoice_id = :invoice_id";
        $params[':invoice_id'] = $search_invoice_id;
    }

    if (!empty($start_date)) {
        $conditions[] = "sr.return_date >= :start_date";
        $params[':start_date'] = $start_date;
    }

    if (!empty($end_date)) {
        $conditions[] = "sr.return_date <= :end_date";
        $params[':end_date'] = $end_date;
    }

    if (!empty($conditions)) {
        $query .= " WHERE " . implode(" AND ", $conditions);
    }
    
    $query .= " ORDER BY sr.return_date DESC";
    
    $stmt = $conn->prepare($query);
    $stmt->execute($params);
    
    $returns = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching sales returns: " . $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 {
            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, #E74C3C, #C0392B);
            border: none;
            color: #fff;
        }

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

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

        .btn-back:hover {
            background: linear-gradient(45deg, #8E44AD, #7D3C98);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(155, 89, 182, 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-undo me-2"></i> فواتير مرتجع المبيعات</h2>

            <!-- نموذج البحث -->
            <form method="GET" class="row g-3 mb-4">
                <div class="col-md-3">
                    <label class="form-label"><i class="fas fa-file-invoice"></i> رقم الفاتورة</label>
                    <input type="number" class="form-control" name="search_invoice_id" value="<?php echo $search_invoice_id ?: ''; ?>" placeholder="ابحث برقم الفاتورة">
                </div>
                <div class="col-md-3">
                    <label class="form-label"><i class="fas fa-calendar-day"></i> من تاريخ</label>
                    <input type="date" class="form-control" name="start_date" value="<?php echo $start_date ?: ''; ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label"><i class="fas fa-calendar-day"></i> إلى تاريخ</label>
                    <input type="date" class="form-control" name="end_date" value="<?php echo $end_date ?: ''; ?>">
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <button type="submit" class="btn btn-search w-100"><i class="fas fa-search"></i> بحث</button>
                </div>
            </form>

            <!-- جدول فواتير المرتجعات -->
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>رقم المرتجع</th>
                            <th>رقم الفاتورة</th>
                            <th>اسم العميل</th>
                            <th>المبلغ المرتجع</th>
                            <th>تاريخ المرتجع</th>
                            <th>الخزنة</th>
                            <th>إجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($returns)): ?>
                            <tr>
                                <td colspan="7" class="text-center">لا توجد فواتير مرتجعات!</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($returns as $return): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($return['id']); ?></td>
                                    <td><?php echo htmlspecialchars($return['invoice_id']); ?></td>
                                    <td><?php echo htmlspecialchars($return['customer_name'] ?? 'غير محدد'); ?></td>
                                    <td><?php echo number_format($return['amount'], 2); ?> ج.م</td>
                                    <td><?php echo htmlspecialchars($return['return_date']); ?></td>
                                    <td><?php echo htmlspecialchars($return['treasury_name'] ?? 'غير محدد'); ?></td>
                                    <td>
                                        <a href="print_sales_return.php?return_id=<?php echo $return['id']; ?>" class="btn btn-print" target="_blank">
                                            <i class="fas fa-print"></i> طباعة
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <div class="text-center mt-3">
                <button class="btn btn-back" onclick="window.location.href='dashboard.php'"><i class="fas fa-arrow-right"></i> العودة إلى لوحة التحكم</button>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>