<?php
// pages/edit_request.php
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/functions.php';

if (!isset($_GET['id'])) {
    echo "<div class='alert alert-danger'>رقم الطلب غير موجود</div>";
    require_once __DIR__ . '/../includes/footer.php';
    exit;
}

$req_id = $_GET['id'];
$user_id = $_SESSION['id'];
$user_role = $_SESSION['role'];

// جلب بيانات الطلب مع بيانات المواد (Items) والمرفقات
$stmt = $pdo->prepare("SELECT * FROM requests WHERE id = ?");
$stmt->execute([$req_id]);
$request = $stmt->fetch();

if (!$request) {
    echo "<div class='alert alert-danger'>الطلب غير موجود</div>";
    require_once __DIR__ . '/../includes/footer.php';
    exit;
}

// --- منطق التحقق من الصلاحية (مهم جداً) ---
$can_edit = false;

// 1. سوبر أدمن
if ($user_role == 'super_admin') {
    $can_edit = true;
}
// 2. المشتريات (يعدل أي طلب لم ينتهِ بعد)
elseif ($user_role == 'purchasing' && !in_array($request['status'], ['approved', 'rejected', 'completed'])) {
    $can_edit = true;
}
// 3. صاحب الطلب (يعدل فقط إذا كانت الحالة 'returned')
elseif ($request['user_id'] == $user_id && $request['status'] == 'returned') {
    $can_edit = true;
}

if (!$can_edit) {
    echo "<div class='alert alert-danger text-center mt-5'>عذراً، لا تملك صلاحية تعديل هذا الطلب في حالته الحالية.</div>";
    require_once __DIR__ . '/../includes/footer.php';
    exit;
}

$msg = "";

// --- معالجة الحفظ (POST) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        $pdo->beginTransaction();

        // تحديد الحالة بعد التعديل
        if ($user_role == 'purchasing') {
            // إذا عدل المشتري، يبقى الطلب في مرحلة التدقيق المالي
            $new_status = 'pending_purchasing';
        } else {
            // إذا عدل الموظف، يعود الطلب للمدير المباشر (مدير الإدارة)
            $new_status = ($request['request_type'] == 'sports') ? 'pending_manager' : 'pending_purchasing';
        }

        // تحديث البيانات الأساسية (رياضي + إداري)
        $sql = "UPDATE requests SET 
                status = ?,
                sports_team_name = ?, match_opponent = ?, match_type = ?, 
                match_date = ?, match_time = ?, departure_time = ?, 
                match_location = ?, transport_type = ?, number_of_persons = ?, 
                cash_allowance = ?, meal_lunch_qty = ?, meal_lunch_time = ?, 
                meal_dinner_qty = ?, meal_dinner_time = ?, requester_notes = ?,
                admin_department_name = ?, required_delivery_date = ?, 
                updated_at = NOW() 
                WHERE id = ?";
        
        $pdo->prepare($sql)->execute([
            $new_status,
            $_POST['sports_team_name'] ?? $request['sports_team_name'],
            $_POST['match_opponent'] ?? $request['match_opponent'],
            $_POST['match_type'] ?? $request['match_type'],
            $_POST['match_date'] ?? $request['match_date'],
            $_POST['match_time'] ?? $request['match_time'],
            $_POST['departure_time'] ?? $request['departure_time'],
            $_POST['match_location'] ?? $request['match_location'],
            $_POST['transport_type'] ?? $request['transport_type'],
            $_POST['number_of_persons'] ?? $request['number_of_persons'],
            $_POST['cash_allowance'] ?? $request['cash_allowance'],
            $_POST['meal_lunch_qty'] ?? $request['meal_lunch_qty'],
            $_POST['meal_lunch_time'] ?? $request['meal_lunch_time'],
            $_POST['meal_dinner_qty'] ?? $request['meal_dinner_qty'],
            $_POST['meal_dinner_time'] ?? $request['meal_dinner_time'],
            $_POST['requester_notes'] ?? $request['requester_notes'],
            $_POST['admin_department_name'] ?? $request['admin_department_name'],
            $_POST['required_delivery_date'] ?? $request['required_delivery_date'],
            $req_id
        ]);

        // إذا كان إدارياً، نقوم بتحديث المواد
        if ($request['request_type'] == 'admin' && isset($_POST['items'])) {
            $pdo->prepare("DELETE FROM request_items WHERE request_id = ?")->execute([$req_id]);
            $item_stmt = $pdo->prepare("INSERT INTO request_items (request_id, item_name, quantity, unit_price, details) VALUES (?, ?, ?, ?, ?)");
            foreach ($_POST['items'] as $item) {
                if (!empty($item['name'])) {
                    $item_stmt->execute([$req_id, $item['name'], $item['qty'], $item['price'], $item['details']]);
                }
            }
        }

        $pdo->prepare("INSERT INTO audit_logs (user_id, request_id, action_type, details, ip_address) VALUES (?, ?, 'edit', ?, ?)")
            ->execute([$user_id, $req_id, "تعديل الطلب بواسطة $user_role", $_SERVER['REMOTE_ADDR']]);

        $pdo->commit();
        $msg = "<div class='alert alert-success text-center fw-bold'>تم حفظ التعديلات بنجاح! جاري التحويل...</div><script>setTimeout(function(){ window.location.href='view_request.php?id=$req_id'; }, 2000);</script>";
        
        // جلب البيانات المحدثة للعرض
        $stmt->execute([$req_id]);
        $request = $stmt->fetch();

    } catch (Exception $e) {
        $pdo->rollBack();
        $msg = "<div class='alert alert-danger'>خطأ أثناء الحفظ: " . $e->getMessage() . "</div>";
    }
}

$items = $pdo->query("SELECT * FROM request_items WHERE request_id = $req_id")->fetchAll();
?>

<div class="container py-4">
    <div class="row justify-content-center">
        <div class="col-lg-10">
            <?php echo $msg; ?>
            <div class="card shadow border-0">
                <div class="card-header bg-warning py-3 d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 text-dark fw-bold"><i class="bi bi-pencil-square"></i> تعديل الطلب #<?php echo $req_id; ?></h5>
                    <a href="view_request.php?id=<?php echo $req_id; ?>" class="btn btn-sm btn-outline-dark">إلغاء</a>
                </div>
                <div class="card-body p-4">
                    <form method="POST">
                        <?php if ($request['request_type'] == 'sports'): ?>
                            <h6 class="text-success border-bottom pb-2 mb-3">تفاصيل المباراة واللوجستيات</h6>
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">الفريق / القسم</label>
                                    <input type="text" name="sports_team_name" class="form-control" value="<?php echo $request['sports_team_name']; ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">المنافس</label>
                                    <input type="text" name="match_opponent" class="form-control" value="<?php echo $request['match_opponent']; ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">نوع المباراة</label>
                                    <input type="text" name="match_type" class="form-control" value="<?php echo $request['match_type']; ?>" placeholder="دوري، ودية، الخ..">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">التاريخ</label>
                                    <input type="date" name="match_date" class="form-control" value="<?php echo $request['match_date']; ?>" required>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">الوقت</label>
                                    <input type="time" name="match_time" class="form-control" value="<?php echo $request['match_time']; ?>" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">وقت المغادرة</label>
                                    <input type="time" name="departure_time" class="form-control" value="<?php echo $request['departure_time']; ?>">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">المكان</label>
                                    <input type="text" name="match_location" class="form-control" value="<?php echo $request['match_location']; ?>">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">العدد</label>
                                    <input type="number" name="number_of_persons" class="form-control" value="<?php echo $request['number_of_persons']; ?>">
                                </div>
                            </div>

                            <h6 class="text-success border-bottom pb-2 mb-3 mt-4">التغذية والنقل</h6>
                            <div class="row g-3">
                                <div class="col-md-3"><label>غداء (عدد)</label><input type="number" name="meal_lunch_qty" class="form-control" value="<?php echo $request['meal_lunch_qty']; ?>"></div>
                                <div class="col-md-3"><label>وقت الغداء</label><input type="time" name="meal_lunch_time" class="form-control" value="<?php echo $request['meal_lunch_time']; ?>"></div>
                                <div class="col-md-3"><label>عشاء (عدد)</label><input type="number" name="meal_dinner_qty" class="form-control" value="<?php echo $request['meal_dinner_qty']; ?>"></div>
                                <div class="col-md-3"><label>وقت العشاء</label><input type="time" name="meal_dinner_time" class="form-control" value="<?php echo $request['meal_dinner_time']; ?>"></div>
                            </div>
                        <?php else: ?>
                            <h6 class="text-primary border-bottom pb-2 mb-3">بيانات طلب المشتريات</h6>
                            <div class="row g-3 mb-4">
                                <div class="col-md-6">
                                    <label class="form-label">القسم</label>
                                    <input type="text" name="admin_department_name" class="form-control" value="<?php echo $request['admin_department_name']; ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">تاريخ التسليم المطلوب</label>
                                    <input type="date" name="required_delivery_date" class="form-control" value="<?php echo $request['required_delivery_date']; ?>" required>
                                </div>
                            </div>

                            <h6 class="fw-bold">المواد والكميات:</h6>
                            <table class="table table-bordered align-middle" id="itemsTable">
                                <thead class="table-light">
                                    <tr>
                                        <th>اسم المادة</th>
                                        <th style="width: 100px;">الكمية</th>
                                        <th style="width: 150px;">سعر الوحدة</th>
                                        <th>ملاحظات</th>
                                        <th style="width: 50px;"></th>
                                    </tr>
                                </thead>
                                <tbody id="itemsBody">
                                    <?php foreach ($items as $index => $item): ?>
                                    <tr>
                                        <td><input type="text" name="items[<?php echo $index; ?>][name]" class="form-control" value="<?php echo $item['item_name']; ?>" required></td>
                                        <td><input type="number" name="items[<?php echo $index; ?>][qty]" class="form-control" value="<?php echo $item['quantity']; ?>" required></td>
                                        <td><input type="number" step="0.01" name="items[<?php echo $index; ?>][price]" class="form-control" value="<?php echo $item['unit_price']; ?>"></td>
                                        <td><input type="text" name="items[<?php echo $index; ?>][details]" class="form-control" value="<?php echo $item['details']; ?>"></td>
                                        <td><button type="button" class="btn btn-danger btn-sm" onclick="this.closest('tr').remove()"><i class="bi bi-trash"></i></button></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                            <button type="button" class="btn btn-sm btn-outline-primary mb-4" onclick="addRow()">+ إضافة مادة</button>
                        <?php endif; ?>

                        <div class="mt-4">
                            <label class="fw-bold">ملاحظات إضافية:</label>
                            <textarea name="requester_notes" class="form-control" rows="2"><?php echo $request['requester_notes']; ?></textarea>
                        </div>

                        <div class="mt-5 text-center">
                            <button type="submit" class="btn btn-success btn-lg px-5 shadow">
                                <i class="bi bi-save"></i> حفظ جميع التعديلات
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    let itemIndex = <?php echo count($items); ?>;
    function addRow() {
        const tbody = document.getElementById('itemsBody');
        const row = `
            <tr>
                <td><input type="text" name="items[${itemIndex}][name]" class="form-control" required></td>
                <td><input type="number" name="items[${itemIndex}][qty]" class="form-control" required></td>
                <td><input type="number" step="0.01" name="items[${itemIndex}][price]" class="form-control"></td>
                <td><input type="text" name="items[${itemIndex}][details]" class="form-control"></td>
                <td><button type="button" class="btn btn-danger btn-sm" onclick="this.closest('tr').remove()"><i class="bi bi-trash"></i></button></td>
            </tr>
        `;
        tbody.insertAdjacentHTML('beforeend', row);
        itemIndex++;
    }
</script>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>