<?php
session_start();

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

require_once 'db_connect.php';

// جلب الفاتورة بناءً على رقم الفاتورة (invoice_number)
$invoice = null;
$invoice_items = [];
$invoice_number = isset($_GET['invoice_number']) ? intval($_GET['invoice_number']) : (isset($_POST['invoice_number']) ? intval($_POST['invoice_number']) : 0);
$invoice_id = 0;
$treasury_error = '';
$items_error = '';

if ($invoice_number > 0) {
    try {
        // جلب بيانات فاتورة الشراء بناءً على invoice_number (بدون اعتماد على supplier_name)
        $stmt = $conn->prepare("
            SELECT pi.id, pi.invoice_number, pi.total, pi.treasury_id, pi.paid_amount, pi.remaining_amount, 
                   t.name AS treasury_name 
            FROM purchase_invoices pi 
            LEFT JOIN treasuries t ON pi.treasury_id = t.id 
            WHERE pi.invoice_number = :invoice_number
        ");
        $stmt->execute([':invoice_number' => $invoice_number]);
        $invoice = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($invoice) {
            $invoice_id = $invoice['id'];
            
            if (!$invoice['treasury_id'] || !$invoice['treasury_name']) {
                $treasury_error = "الفاتورة موجودة ولكن الخزنة المرتبطة غير موجودة. يرجى تعديل الخزنة في الفاتورة.";
                $invoice = null;
            } else {
                // جلب تفاصيل المنتجات في الفاتورة باستخدام invoice_id
                $stmt = $conn->prepare("
                    SELECT 
                        pii.id, pii.item_id, pii.quantity AS purchased_quantity, pii.price, 
                        i.name AS product_name, i.quantity AS current_quantity,
                        COALESCE(SUM(pri.quantity), 0) AS returned_quantity
                    FROM purchase_invoice_items pii 
                    LEFT JOIN items i ON pii.item_id = i.id 
                    LEFT JOIN purchase_return_items pri ON pri.product_id = pii.item_id 
                        AND pri.return_id IN (SELECT id FROM purchase_returns WHERE invoice_id = :invoice_id)
                    WHERE pii.invoice_id = :invoice_id
                    GROUP BY pii.id, pii.item_id, pii.quantity, pii.price, i.name, i.quantity
                ");
                $stmt->execute([':invoice_id' => $invoice_id]);
                $invoice_items = $stmt->fetchAll(PDO::FETCH_ASSOC);

                if (empty($invoice_items)) {
                    $items_error = "لا توجد منتجات مرتبطة بهذه الفاتورة! يرجى التحقق من تفاصيل الفاتورة.";
                }
            }
        }
    } catch (PDOException $e) {
        error_log("Error fetching purchase invoice: " . $e->getMessage());
        echo "<pre>Error: " . $e->getMessage() . "</pre>";
    }
}

// معالجة حفظ مرتجع الشراء
$success_message = '';
$error_message = '';
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['save_return'])) {
    $invoice_number = intval($_POST['invoice_number']);
    $invoice_id = intval($_POST['invoice_id']);
    $treasury_id = intval($_POST['treasury_id']);
    $return_date = trim($_POST['return_date']);
    $quantities = $_POST['quantities'] ?? [];

    // حساب المبلغ المرتجع
    $total_return_amount = 0;
    $debug_message = '';
    foreach ($invoice_items as $item) {
        $return_quantity = isset($quantities[$item['id']]) ? intval($quantities[$item['id']]) : 0;
        $debug_message .= "Item ID: {$item['id']}, Return Quantity: $return_quantity, Purchased: {$item['purchased_quantity']}, Returned: {$item['returned_quantity']}, Current: {$item['current_quantity']}<br>";
        if ($return_quantity > 0 && $return_quantity <= ($item['purchased_quantity'] - $item['returned_quantity'])) {
            $total_return_amount += $return_quantity * $item['price'];
            $debug_message .= "Added to total: " . ($return_quantity * $item['price']) . "<br>";
        } else {
            $debug_message .= "Invalid quantity for item {$item['id']}<br>";
        }
    }

    if ($invoice_id > 0 && $treasury_id > 0 && $total_return_amount > 0 && !empty($return_date)) {
        try {
            $conn->beginTransaction();

            // تسجيل مرتجع الشراء
            $stmt = $conn->prepare("INSERT INTO purchase_returns (invoice_id, treasury_id, amount, return_date) VALUES (:invoice_id, :treasury_id, :amount, :return_date)");
            $stmt->execute([
                ':invoice_id' => $invoice_id,
                ':treasury_id' => $treasury_id,
                ':amount' => $total_return_amount,
                ':return_date' => $return_date
            ]);
            $return_id = $conn->lastInsertId();

            // تسجيل تفاصيل المرتجعات
            foreach ($invoice_items as $item) {
                $return_quantity = isset($quantities[$item['id']]) ? intval($quantities[$item['id']]) : 0;
                if ($return_quantity > 0 && $return_quantity <= ($item['purchased_quantity'] - $item['returned_quantity'])) {
                    $stmt = $conn->prepare("INSERT INTO purchase_return_items (return_id, product_id, quantity, unit_price) VALUES (:return_id, :product_id, :quantity, :unit_price)");
                    $stmt->execute([
                        ':return_id' => $return_id,
                        ':product_id' => $item['item_id'],
                        ':quantity' => $return_quantity,
                        ':unit_price' => $item['price']
                    ]);
                }
            }

            // تحديث المخزون في جدول items
            foreach ($invoice_items as $item) {
                $return_quantity = isset($quantities[$item['id']]) ? intval($quantities[$item['id']]) : 0;
                if ($return_quantity > 0 && $return_quantity <= ($item['purchased_quantity'] - $item['returned_quantity'])) {
                    $stmt = $conn->prepare("UPDATE items SET quantity = quantity - :quantity WHERE id = :item_id AND quantity >= :quantity");
                    $stmt->execute([
                        ':quantity' => $return_quantity,
                        ':item_id' => $item['item_id']
                    ]);
                    if ($stmt->rowCount() == 0) {
                        throw new Exception("الكمية في المخزون غير كافية لإتمام المرتجع!");
                    }
                }
            }

            // إضافة المبلغ إلى الخزنة (لأننا بنرجع بضاعة، يعني بنسترد فلوس)
            $stmt = $conn->prepare("UPDATE treasuries SET current_balance = current_balance + :amount WHERE id = :treasury_id");
            $stmt->execute([':amount' => $total_return_amount, ':treasury_id' => $treasury_id]);

            // تسجيل العملية في treasury_transactions
            $description = "مرتجع شراء للفاتورة #$invoice_number";
            $stmt = $conn->prepare("INSERT INTO treasury_transactions (treasury_id, amount, transaction_type, description, date) VALUES (:treasury_id, :amount, 'deposit', :description, :date)");
            $stmt->execute([
                ':treasury_id' => $treasury_id,
                ':amount' => $total_return_amount,
                ':description' => $description,
                ':date' => $return_date
            ]);

            $conn->commit();
            $success_message = "تم تسجيل مرتجع الشراء بنجاح وإضافة المبلغ إلى الخزنة!";
            header("Location: purchase_return.php?invoice_number=$invoice_number");
            exit();
        } catch (PDOException $e) {
            $conn->rollBack();
            error_log("Error saving purchase return: " . $e->getMessage());
            $error_message = "فشل تسجيل مرتجع الشراء: " . $e->getMessage();
        } catch (Exception $e) {
            $conn->rollBack();
            error_log("Error: " . $e->getMessage());
            $error_message = $e->getMessage();
        }
    } else {
        $error_message = "فشل الحفظ: التحقق: Invoice Number = $invoice_number, Invoice ID = $invoice_id, Treasury ID = $treasury_id, Total = $total_return_amount, Date = '$return_date'. <br>تفاصيل: $debug_message";
    }
}
?>

<!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-save {
            background: linear-gradient(45deg, #2ECC71, #27AE60);
            border: none;
            color: #fff;
        }

        .btn-save:hover {
            background: linear-gradient(45deg, #27AE60, #219653);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(46, 204, 113, 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>
            <?php if (!empty($success_message)): ?>
                <div class="success-message" style="color: #2ECC71; text-align: center; margin-bottom: 20px;">
                    <?php echo $success_message; ?>
                </div>
            <?php endif; ?>
            <?php if (!empty($error_message)): ?>
                <div class="error-message" style="color: #E74C3C; text-align: center; margin-bottom: 20px;">
                    <?php echo nl2br($error_message); ?>
                </div>
            <?php endif; ?>
            <?php if (!empty($treasury_error)): ?>
                <div class="error-message" style="color: #E74C3C; text-align: center; margin-bottom: 20px;">
                    <?php echo $treasury_error; ?>
                </div>
            <?php endif; ?>
            <?php if (!empty($items_error)): ?>
                <div class="error-message" style="color: #E74C3C; text-align: center; margin-bottom: 20px;">
                    <?php echo $items_error; ?>
                </div>
            <?php endif; ?>

            <!-- نموذج البحث عن الفاتورة -->
            <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="invoice_number" value="<?php echo $invoice_number ?: ''; ?>" required>
                </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>

            <?php if ($invoice && empty($items_error)): ?>
                <form method="POST" class="row g-3">
                    <input type="hidden" name="invoice_number" value="<?php echo $invoice['invoice_number']; ?>">
                    <input type="hidden" name="invoice_id" value="<?php echo $invoice['id']; ?>">
                    <input type="hidden" name="treasury_id" value="<?php echo $invoice['treasury_id']; ?>">

                    <div class="col-md-3">
                        <label class="form-label"><i class="fas fa-user"></i> اسم المورد</label>
                        <input type="text" class="form-control" value="غير محدد" readonly>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label"><i class="fas fa-lock"></i> الخزنة</label>
                        <input type="text" class="form-control" value="<?php echo htmlspecialchars($invoice['treasury_name']); ?>" readonly>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label"><i class="fas fa-money-bill"></i> المبلغ الكلي للفاتورة</label>
                        <input type="text" class="form-control" value="<?php echo number_format($invoice['total'], 2); ?> ج.م" readonly>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label"><i class="fas fa-money-check"></i> المدفوع</label>
                        <input type="text" class="form-control" value="<?php echo number_format($invoice['paid_amount'], 2); ?> ج.م" readonly>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label"><i class="fas fa-money-bill-wave"></i> المتبقي</label>
                        <input type="text" class="form-control" value="<?php echo number_format($invoice['remaining_amount'], 2); ?> ج.م" readonly>
                    </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="return_date" value="<?php echo date('Y-m-d'); ?>" required>
                    </div>

                    <!-- جدول المنتجات -->
                    <div class="table-responsive mt-3">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>اسم المنتج</th>
                                    <th>الكمية المشتراة</th>
                                    <th>الكمية المرتجعة</th>
                                    <th>الكمية المتبقية</th>
                                    <th>الكمية الحالية</th>
                                    <th>سعر الوحدة</th>
                                    <th>الإجمالي</th>
                                    <th>الكمية المرتجعة (جديد)</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($invoice_items as $item): ?>
                                    <?php $remaining_quantity = $item['purchased_quantity'] - $item['returned_quantity']; ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($item['product_name'] ?? 'غير معروف'); ?></td>
                                        <td><?php echo htmlspecialchars($item['purchased_quantity']); ?></td>
                                        <td><?php echo htmlspecialchars($item['returned_quantity']); ?></td>
                                        <td><?php echo htmlspecialchars($remaining_quantity); ?></td>
                                        <td><?php echo htmlspecialchars($item['current_quantity']); ?></td>
                                        <td><?php echo number_format($item['price'], 2); ?> ج.م</td>
                                        <td><?php echo number_format($item['purchased_quantity'] * $item['price'], 2); ?> ج.م</td>
                                        <td>
                                            <input type="number" class="form-control" name="quantities[<?php echo $item['id']; ?>]" min="0" max="<?php echo $remaining_quantity; ?>" value="0">
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <div class="col-md-12 text-center mt-3">
                        <button type="submit" class="btn btn-save" name="save_return"><i class="fas fa-save"></i> حفظ المرتجع</button>
                    </div>
                </form>
            <?php elseif ($invoice_number > 0 && empty($items_error)): ?>
                <div style="color: #E74C3C; text-align: center; margin-bottom: 20px;">
                    لم يتم العثور على فاتورة بهذا الرقم! تأكد من الرقم أو أضف فاتورة أولاً.
                </div>
            <?php endif; ?>

            <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>