<?php
session_start();

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

require_once 'db_connect.php';




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




// جلب العملاء
$clients = [];
try {
    $clients = $conn->query("SELECT id, name FROM clients ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching clients: " . $e->getMessage());
    $clients = [];
}

// جلب المستخدمين
$users = [];
try {
    $users = $conn->query("SELECT id, username FROM users ORDER BY username ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching users: " . $e->getMessage());
    $users = [];
}

// معالجة البحث
$invoices = [];
$totals = ['total' => 0, 'paid_total' => 0, 'remaining_total' => 0];
$conditions = [];
$params = [];

$invoice_number = $_GET['invoice_number'] ?? '';
$user_id_filter = $_GET['user_id'] ?? '';
$client_id = $_GET['client_id'] ?? '';
$payment_type = $_GET['payment_type'] ?? '';
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] . ' 00:00:00' : date('Y-m-d 00:00:00', strtotime('-30 days'));
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] . ' 23:59:59' : date('Y-m-d 23:59:59');

if (!empty($invoice_number)) {
    $conditions[] = "si.invoice_number = :invoice_number";
    $params[':invoice_number'] = $invoice_number;
}
if (!empty($user_id_filter)) {
    $conditions[] = "si.user_id = :user_id";
    $params[':user_id'] = $user_id_filter;
}
if (!empty($client_id)) {
    $conditions[] = "si.client_id = :client_id";
    $params[':client_id'] = $client_id;
}
if (!empty($payment_type)) {
    $conditions[] = "si.payment_type = :payment_type";
    $params[':payment_type'] = $payment_type;
}
$conditions[] = "si.date BETWEEN :start_date AND :end_date";
$params[':start_date'] = $start_date;
$params[':end_date'] = $end_date;

$where_clause = !empty($conditions) ? "WHERE " . implode(" AND ", $conditions) : "";

try {
    // جلب الفواتير
    $query = "SELECT si.*, c.name AS client_name, u.username AS user_name 
              FROM sales_invoices si 
              LEFT JOIN clients c ON si.client_id = c.id 
              LEFT JOIN users u ON si.user_id = u.id 
              $where_clause 
              ORDER BY si.date DESC";
    $stmt = $conn->prepare($query);
    $stmt->execute($params);
    $invoices = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // جلب الإجماليات
    $totals_query = "SELECT 
        SUM(si.final_total) AS total,
        SUM(si.paid_amount) AS paid_total,
        SUM(si.remaining_amount) AS remaining_total
        FROM sales_invoices si 
        $where_clause";
    $stmt = $conn->prepare($totals_query);
    $stmt->execute($params);
    $totals = $stmt->fetch(PDO::FETCH_ASSOC) ?: ['total' => 0, 'paid_total' => 0, 'remaining_total' => 0];
} catch (PDOException $e) {
    error_log("Error fetching invoices: " . $e->getMessage());
    $invoices = [];
}

// معالجة الحذف
$success_message = '';
$error_message = '';

if (isset($_GET['delete']) && $_GET['delete'] > 0) {
    $delete_id = $_GET['delete'];
    try {
        $conn->beginTransaction();

        // جلب تفاصيل الأصناف لإعادة الكميات
        $stmt = $conn->prepare("SELECT item_id, quantity FROM sales_invoice_items WHERE invoice_id = :invoice_id");
        $stmt->execute([':invoice_id' => $delete_id]);
        $items_to_restore = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // إعادة الكميات إلى items.quantity
        foreach ($items_to_restore as $item) {
            $stmt = $conn->prepare("UPDATE items SET quantity = quantity + :quantity WHERE id = :item_id");
            $stmt->execute([':quantity' => $item['quantity'], ':item_id' => $item['item_id']]);
        }

        // حذف تفاصيل الفاتورة
        $stmt = $conn->prepare("DELETE FROM sales_invoice_items WHERE invoice_id = :invoice_id");
        $stmt->execute([':invoice_id' => $delete_id]);

        // حذف الفاتورة
        $stmt = $conn->prepare("DELETE FROM sales_invoices WHERE id = :id");
        $stmt->execute([':id' => $delete_id]);

        // تحديث الخزنة إذا كان الدفع نقديًا
        $stmt = $conn->prepare("SELECT treasury_id, final_total, payment_type FROM sales_invoices WHERE id = :id");
        $stmt->execute([':id' => $delete_id]);
        $invoice = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($invoice && $invoice['payment_type'] === 'cash') {
            $stmt = $conn->prepare("UPDATE treasuries SET current_balance = current_balance - :final_total WHERE id = :treasury_id");
            $stmt->execute([':final_total' => $invoice['final_total'], ':treasury_id' => $invoice['treasury_id']]);
        }

        $conn->commit();
        $success_message = "تم حذف الفاتورة بنجاح!";
    } catch (Exception $e) {
        $conn->rollBack();
        error_log("Error deleting invoice: " . $e->getMessage());
        $error_message = "فشل حذف الفاتورة: " . $e->getMessage();
    }
}

// معالجة التعديل (تحتاج إلى صفحة منفصلة للتعديل)
$editing = false;
$edit_invoice = null;
$edit_items = [];
if (isset($_GET['edit']) && $_GET['edit'] > 0) {
    $edit_id = $_GET['edit'];
    try {
        $stmt = $conn->prepare("SELECT si.*, c.name AS client_name 
                                FROM sales_invoices si 
                                LEFT JOIN clients c ON si.client_id = c.id 
                                WHERE si.id = :id");
        $stmt->execute([':id' => $edit_id]);
        $edit_invoice = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($edit_invoice) {
            $editing = true;
            $stmt = $conn->prepare("SELECT sii.*, i.name AS item_name 
                                    FROM sales_invoice_items sii 
                                    LEFT JOIN items i ON sii.item_id = i.id 
                                    WHERE sii.invoice_id = :invoice_id");
            $stmt->execute([':invoice_id' => $edit_id]);
            $edit_items = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
    } catch (PDOException $e) {
        error_log("Error fetching invoice for edit: " . $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, .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, #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-totals {
            background: linear-gradient(45deg, #F1C40F, #D4AC0D);
            border: none;
            color: #fff;
        }

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

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

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

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

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

        .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%;
            margin-top: 20px;
        }

        .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-file-invoice me-2"></i> إدارة فواتير المبيعات</h2>
            <?php if ($success_message): ?>
                <div class="success-message"><?php echo $success_message; ?></div>
            <?php endif; ?>
            <?php if ($error_message): ?>
                <div class="error-message"><?php echo $error_message; ?></div>
            <?php endif; ?>

            <!-- نموذج البحث -->
            <form method="GET" class="mb-4">
                <div class="row g-3">
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-hashtag"></i> رقم الفاتورة</label>
                        <input type="text" class="form-control" name="invoice_number" value="<?php echo htmlspecialchars($invoice_number); ?>">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-user"></i> المستخدم</label>
                        <select class="form-select" name="user_id">
                            <option value="">كل المستخدمين</option>
                            <?php foreach ($users as $user): ?>
                                <option value="<?php echo $user['id']; ?>" <?php echo $user_id_filter == $user['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($user['username']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-user-tie"></i> العميل</label>
                        <select class="form-select" name="client_id">
                            <option value="">كل العملاء</option>
                            <?php foreach ($clients as $client): ?>
                                <option value="<?php echo $client['id']; ?>" <?php echo $client_id == $client['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($client['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-money-check"></i> نوع الدفع</label>
                        <select class="form-select" name="payment_type">
                            <option value="">الكل</option>
                            <option value="cash" <?php echo $payment_type == 'cash' ? 'selected' : ''; ?>>نقدي</option>
                            <option value="credit" <?php echo $payment_type == 'credit' ? 'selected' : ''; ?>>آجل</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-calendar"></i> من تاريخ</label>
                        <input type="date" class="form-control" name="start_date" value="<?php echo isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d', strtotime('-30 days')); ?>">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-calendar"></i> إلى تاريخ</label>
                        <input type="date" class="form-control" name="end_date" value="<?php echo isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d'); ?>">
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-search"><i class="fas fa-search"></i> بحث</button>
                    </div>
                    <div class="col-md-2">
                        <button type="button" class="btn btn-totals" data-bs-toggle="modal" data-bs-target="#totalsModal"><i class="fas fa-calculator"></i> عرض الإجمالي</button>
                    </div>
                </div>
            </form>

            <!-- جدول الفواتير -->
            <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($invoices)): ?>
                            <?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['user_name']); ?></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>
                                    <td><?php echo $invoice['payment_type'] == 'cash' ? 'نقدي' : 'آجل'; ?></td>
                                    <td><?php echo date('Y-m-d H:i', strtotime($invoice['date'])); ?></td>
                                    <td>
                                    <td>
    <a href="edit_sales_invoice.php?id=<?php echo $invoice['id']; ?>&return_url=<?php echo urlencode($_SERVER['REQUEST_URI']); ?>" class="btn btn-edit btn-sm"><i class="fas fa-edit"></i> تعديل</a>
    <a href="?delete=<?php echo $invoice['id']; ?>&invoice_number=<?php echo urlencode($invoice_number); ?>&user_id=<?php echo urlencode($user_id_filter); ?>&client_id=<?php echo urlencode($client_id); ?>&payment_type=<?php echo urlencode($payment_type); ?>&start_date=<?php echo isset($_GET['start_date']) ? $_GET['start_date'] : ''; ?>&end_date=<?php echo isset($_GET['end_date']) ? $_GET['end_date'] : ''; ?>" class="btn btn-delete btn-sm" onclick="return confirm('هل أنت متأكد من حذف هذه الفاتورة؟');"><i class="fas fa-trash"></i> حذف</a>
</td>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="9" style="text-align: center; color: #E74C3C;">لا توجد فواتير في هذه الفترة.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- نافذة الإجمالي -->
            <div class="modal fade" id="totalsModal" tabindex="-1" aria-labelledby="totalsModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="totalsModalLabel">إجمالي المبيعات</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <p><strong>إجمالي المبيعات:</strong> <?php echo number_format($totals['total'], 2); ?> ج.م</p>
                            <p><strong>إجمالي المدفوع:</strong> <?php echo number_format($totals['paid_total'], 2); ?> ج.م</p>
                            <p><strong>إجمالي المتبقي:</strong> <?php echo number_format($totals['remaining_total'], 2); ?> ج.م</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إغلاق</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

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