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

$msg = "";

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $req_type = $_POST['request_type'];
    $user_id = $_SESSION['id'];
    
    // تحديد الحالة الأولية بناءً على النوع
    // رياضي -> يذهب لمدير الإدارة (pending_manager)
    // إداري -> يذهب للمشتريات (pending_purchasing)
    $initial_status = ($req_type == 'sports') ? 'pending_manager' : 'pending_purchasing';
    
    try {
        $pdo->beginTransaction();

        // 1. إدخال الطلب (كما في الكود الأصلي)
        $sql = "INSERT INTO requests (
            user_id, request_type, status, category,
            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
        ) VALUES (
            ?, ?, ?, ?,
            ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 
            ?, ?, ?, ?, ?,
            ?, ?
        )";

        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            $user_id, 
            $req_type, 
            $initial_status,
            $_POST['category'] ?? null,
            $_POST['sports_team_name'] ?? null,
            $_POST['match_opponent'] ?? null,
            $_POST['match_type'] ?? null,
            $_POST['match_date'] ?? null,
            $_POST['match_time'] ?? null,
            $_POST['departure_time'] ?? null,
            $_POST['match_location'] ?? null,
            $_POST['transport_type'] ?? null,
            $_POST['number_of_persons'] ?? null,
            $_POST['cash_allowance'] ?? null,
            $_POST['meal_lunch_qty'] ?? null,
            $_POST['meal_lunch_time'] ?? null,
            $_POST['meal_dinner_qty'] ?? null,
            $_POST['meal_dinner_time'] ?? null,
            $_POST['requester_notes'] ?? null,
            $_POST['admin_department_name'] ?? null,
            $_POST['required_delivery_date'] ?? null
        ]);
        
        $request_id = $pdo->lastInsertId();

        // 2. إدخال العناصر (Items)
        if (isset($_POST['items']) && is_array($_POST['items'])) {
            $sql_item = "INSERT INTO request_items (request_id, item_name, quantity, estimated_price, details) VALUES (?, ?, ?, ?, ?)";
            $stmt_item = $pdo->prepare($sql_item);

            foreach ($_POST['items'] as $item) {
                if (!empty($item['name'])) {
                    $stmt_item->execute([
                        $request_id, 
                        $item['name'], 
                        $item['qty'], 
                        $item['price'] ?? 0, 
                        $item['details'] ?? ''
                    ]);
                }
            }
        }

        // 3. رفع المرفقات
        if (!empty($_FILES['attachments']['name'][0])) {
            $upload_dir = '../assets/uploads/docs/';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);

            foreach ($_FILES['attachments']['name'] as $key => $name) {
                if ($_FILES['attachments']['error'][$key] == 0) {
                    $tmp_name = $_FILES['attachments']['tmp_name'][$key];
                    $filename = time() . '_' . basename($name);
                    move_uploaded_file($tmp_name, $upload_dir . $filename);

                    $pdo->prepare("INSERT INTO attachments (request_id, uploaded_by_user_id, file_path) VALUES (?, ?, ?)")
                        ->execute([$request_id, $user_id, 'assets/uploads/docs/' . $filename]);
                }
            }
        }

        $pdo->commit();
        
        // إشعار
        // sendNotificationEmail(...);

        $msg = "<div class='alert alert-success'>✅ تم إرسال الطلب بنجاح رقم #$request_id</div>";

    } catch (PDOException $e) {
        $pdo->rollBack();
        $msg = "<div class='alert alert-danger'>خطأ: " . $e->getMessage() . "</div>";
    }
}
?>

<div class="container mt-5 mb-5">
    <div class="row justify-content-center">
        <div class="col-md-10">
            <div class="card shadow-lg border-0 rounded-3">
                <div class="card-header bg-gradient bg-primary text-white py-3">
                    <h4 class="mb-0"><i class="bi bi-plus-circle-dotted me-2"></i> إنشاء طلب جديد</h4>
                </div>
                <div class="card-body p-4 bg-light">
                    
                    <?php if ($msg) echo $msg; ?>

                    <div class="d-flex justify-content-center gap-3 mb-4">
                        <?php 
                        // ========================================================
                        // منطق عرض الأزرار (هنا التعديل الوحيد لإضافة المحاسب)
                        // ========================================================
                        $role = $_SESSION['role'];
                        
                        // 1. زر الطلب الرياضي (يظهر للفئات الرياضية فقط)
                        if (in_array($role, ['super_admin', 'ceo', 'manager_first', 'manager_youth', 'coach', 'staff_first', 'staff_youth', 'supervisor'])) {
                            echo '<button type="button" onclick="toggleForm(\'sports\')" class="btn btn-outline-success btn-lg px-4"><i class="bi bi-trophy"></i> طلب قطاع رياضي</button>';
                        }

                        // 2. زر الطلب الإداري (يظهر للجميع تقريباً + المحاسب)
                        // التعديل: تمت إضافة accountant للقائمة
                        if (in_array($role, ['super_admin', 'ceo', 'manager_first', 'manager_youth', 'purchasing', 'media_manager', 'maintenance_head', 'hr_manager', 'legal_officer', 'requester', 'accountant'])) {
                            echo '<button type="button" onclick="toggleForm(\'admin\')" class="btn btn-outline-primary btn-lg px-4"><i class="bi bi-building"></i> طلب إداري / مشتريات</button>';
                        }
                        ?>
                    </div>

                    <form method="POST" enctype="multipart/form-data" id="sportsForm" style="display: none;">
                        <input type="hidden" name="request_type" value="sports">
                        
                        <div class="card p-3 mb-3 border bg-white">
                            <h6 class="text-success border-bottom pb-2 fw-bold">تفاصيل المباراة / المعسكر</h6>
                            
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">الفئة (Category)</label>
                                    <select name="category" class="form-select" required>
                                        <option value="first_team">الفريق الأول</option>
                                        <option value="youth">المراحل السنية</option>
                                        <option value="other_sports">الألعاب الأخرى</option>
                                    </select>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">الفريق (Team Name)</label>
                                    <input type="text" name="sports_team_name" class="form-control" placeholder="مثال: تحت 19 سنة" required>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">المنافس (Opponent)</label>
                                    <input type="text" name="match_opponent" class="form-control" placeholder="مثال: نادي الجزيرة">
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">نوع المباراة</label>
                                    <select name="match_type" class="form-select" required>
                                        <option value="Official Home">رسمية (أرضنا)</option>
                                        <option value="Official Away">رسمية (خارج أرضنا)</option>
                                        <option value="Friendly Home">ودية (أرضنا)</option>
                                        <option value="Friendly Away">ودية (خارج أرضنا)</option>
                                        <option value="Camp">معسكر</option>
                                    </select>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">التاريخ</label>
                                    <input type="date" name="match_date" class="form-control" required>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">وقت المباراة</label>
                                    <input type="time" name="match_time" class="form-control">
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">وقت المغادرة (للمباريات الخارجية)</label>
                                    <input type="time" name="departure_time" class="form-control">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">مكان المباراة</label>
                                    <input type="text" name="match_location" class="form-control">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">نوع المواصلات</label>
                                    <select name="transport_type" class="form-select">
                                        <option value="">-- غير مطلوب --</option>
                                        <option value="Bus">حافلة النادي</option>
                                        <option value="Rented Bus">حافلة مستأجرة</option>
                                        <option value="Cars">سيارات خاصة</option>
                                    </select>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">عدد الأشخاص (اللاعبين + الجهاز)</label>
                                    <input type="number" name="number_of_persons" class="form-control" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">مصروف الجيب (إن وجد)</label>
                                    <input type="number" step="0.01" name="cash_allowance" class="form-control" placeholder="AED">
                                </div>
                            </div>
                        </div>

                        <div class="card p-3 mb-3 border bg-white">
                            <h6 class="text-warning border-bottom pb-2 fw-bold text-dark">الإعاشة والوجبات</h6>
                            <div class="row">
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">عدد وجبات الغداء</label>
                                    <input type="number" name="meal_lunch_qty" class="form-control">
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">وقت الغداء</label>
                                    <input type="time" name="meal_lunch_time" class="form-control">
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">عدد وجبات العشاء</label>
                                    <input type="number" name="meal_dinner_qty" class="form-control">
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">وقت العشاء</label>
                                    <input type="time" name="meal_dinner_time" class="form-control">
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">ملاحظات إضافية</label>
                            <textarea name="requester_notes" class="form-control" rows="3"></textarea>
                        </div>

                        <div class="mt-4 text-center"><button type="submit" class="btn btn-success btn-lg px-5">إرسال الطلب الرياضي</button></div>
                    </form>

                    <form method="POST" enctype="multipart/form-data" id="adminForm" style="display: none;">
                        <input type="hidden" name="request_type" value="admin">

                        <div class="card p-3 mb-3 border bg-white">
                            <h6 class="text-primary border-bottom pb-2 fw-bold">بيانات الطلب</h6>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">الإدارة / القسم</label>
                                    <select name="admin_department_name" class="form-select" required>
                                        <option value="General">الإدارة العامة</option>
                                        <option value="Finance">المالية</option>
                                        <option value="HR">الموارد البشرية</option>
                                        <option value="Media">الإعلام</option>
                                        <option value="Maintenance">الصيانة والمنشآت</option>
                                        <option value="Store">المخازن</option>
                                        <option value="PR">العلاقات العامة</option>
                                        <option value="Other">أخرى</option>
                                    </select>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">تاريخ التسليم المطلوب</label>
                                    <input type="date" name="required_delivery_date" class="form-control">
                                </div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label fw-bold">المواد / الخدمات المطلوبة</label>
                                <table class="table table-bordered table-sm text-center align-middle">
                                    <thead class="table-light">
                                        <tr>
                                            <th>البيان / الصنف</th>
                                            <th width="100">الكمية</th>
                                            <th width="150">السعر التقديري</th>
                                            <th>ملاحظات</th>
                                            <th width="50"></th>
                                        </tr>
                                    </thead>
                                    <tbody id="itemsBody">
                                        <tr>
                                            <td><input type="text" name="items[0][name]" class="form-control" required></td>
                                            <td><input type="number" name="items[0][qty]" class="form-control" required value="1"></td>
                                            <td><input type="number" step="0.01" name="items[0][price]" class="form-control"></td>
                                            <td><input type="text" name="items[0][details]" class="form-control"></td>
                                            <td></td>
                                        </tr>
                                    </tbody>
                                </table>
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="addRow()">+ إضافة سطر</button>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">مرفقات (عروض أسعار / صور)</label>
                                <input type="file" name="attachments[]" class="form-control" multiple>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">شرح وتفاصيل الطلب</label>
                                <textarea name="requester_notes" class="form-control" rows="3"></textarea>
                            </div>
                        </div>

                        <div class="mt-4 text-center"><button type="submit" class="btn btn-primary btn-lg px-5">رفع الطلب الإداري</button></div>
                    </form>

                </div>
            </div>
        </div>
    </div>
</div>

<script>
    function toggleForm(type) {
        document.getElementById('sportsForm').style.display = 'none';
        document.getElementById('adminForm').style.display = 'none';
        document.getElementById(type + 'Form').style.display = 'block';
    }

    let itemIndex = 1;
    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()\">X</button></td></tr>`;
        tbody.insertAdjacentHTML('beforeend', row);
        itemIndex++;
    }
</script>

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