<?php
/**
 * captains.php - إدارة الكباتن
 * @version 5.0.0
 */

require_once 'config.php';
checkAdminAuth();

// ============================================
// معالجة النماذج
// ============================================

// إضافة كابتن
if (isPost() && isset($_POST['add'])) {
    $name = $conn->real_escape_string($_POST['name']);
    $phone = $conn->real_escape_string($_POST['phone']);
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $vehicle = $conn->real_escape_string($_POST['vehicle']);
    
    $conn->query("INSERT INTO captains (name, phone, password, vehicle_info, created_at) 
                  VALUES ('$name', '$phone', '$password', '$vehicle', NOW())");
    
    $cache->clear();
    $_SESSION['success'] = 'تم إضافة الكابتن بنجاح';
    header('Location: captains.php');
    exit();
}

// تعديل كابتن
if (isPost() && isset($_POST['edit'])) {
    $id = (int)$_POST['id'];
    $name = $conn->real_escape_string($_POST['name']);
    $phone = $conn->real_escape_string($_POST['phone']);
    $vehicle = $conn->real_escape_string($_POST['vehicle']);
    
    if (!empty($_POST['password'])) {
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $conn->query("UPDATE captains SET name='$name', phone='$phone', vehicle_info='$vehicle', password='$password' WHERE id=$id");
    } else {
        $conn->query("UPDATE captains SET name='$name', phone='$phone', vehicle_info='$vehicle' WHERE id=$id");
    }
    
    $cache->clear();
    $_SESSION['success'] = 'تم تعديل الكابتن بنجاح';
    header('Location: captains.php');
    exit();
}

// تغيير حالة الكابتن
if (isPost() && isset($_POST['toggle'])) {
    $id = (int)$_POST['id'];
    $conn->query("UPDATE captains SET status = IF(status='active', 'inactive', 'active') WHERE id=$id");
    
    $cache->clear();
    header('Location: captains.php');
    exit();
}

// حذف كابتن
if (isPost() && isset($_POST['delete'])) {
    $id = (int)$_POST['id'];
    
    // التحقق من وجود طلبات مرتبطة
    $check = $conn->query("SELECT COUNT(*) as count FROM orders WHERE captain_id=$id")->fetch_assoc();
    if ($check['count'] > 0) {
        $_SESSION['error'] = 'لا يمكن حذف الكابتن لوجود طلبات مرتبطة به';
    } else {
        $conn->query("DELETE FROM captains WHERE id=$id");
        $_SESSION['success'] = 'تم حذف الكابتن بنجاح';
    }
    
    $cache->clear();
    header('Location: captains.php');
    exit();
}

// جلب كابتن محدد للتعديل (AJAX)
if (isset($_GET['get_captain'])) {
    $id = (int)$_GET['get_captain'];
    $captain = $conn->query("SELECT id, name, phone, vehicle_info FROM captains WHERE id=$id")->fetch_assoc();
    header('Content-Type: application/json');
    echo json_encode($captain);
    exit();
}

// ============================================
// جلب البيانات
// ============================================

$captains = $cache->get('captains_list');
if (!$captains) {
    $result = $conn->query("
        SELECT c.*, 
               (SELECT COUNT(*) FROM orders WHERE captain_id = c.id) as orders_count 
        FROM captains c 
        ORDER BY c.id DESC 
        LIMIT 200
    ");
    $captains = [];
    while ($row = $result->fetch_assoc()) {
        $captains[] = $row;
    }
    $cache->set('captains_list', $captains, 300);
}

$page_title = 'الكباتن';
include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
.captain-status {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    display: inline-block;
    margin-left: 5px;
}

.status-active { background: #10b981; }
.status-inactive { background: #ef4444; }

.avatar-circle {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background: #FFF3E0;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #F57C00;
    font-size: 1.5rem;
}
</style>

<div class="main-content">
    <div class="top-bar">
        <i class="bi bi-person-badge text-primary fs-4 me-2"></i>
        <span><strong>إدارة الكباتن</strong></span>
        <span class="ms-auto text-muted small">
            <i class="bi bi-grid-3x3-gap-fill me-1"></i><?php echo count($captains); ?> كابتن
        </span>
    </div>

    <!-- زر الإضافة -->
    <div class="d-flex justify-content-end mb-3">
        <button class="btn btn-primary" onclick="openAddModal()">
            <i class="bi bi-plus-lg me-1"></i>إضافة كابتن جديد
        </button>
    </div>

    <!-- Mobile Cards -->
    <div class="row g-3 d-md-none">
        <?php if (empty($captains)): ?>
        <div class="col-12">
            <div class="card text-center p-5">
                <i class="bi bi-person-badge display-1 text-muted mb-3"></i>
                <h6>لا توجد كباتن</h6>
                <p class="text-muted small">قم بإضافة أول كابتن الآن</p>
                <button class="btn btn-primary mx-auto" style="width: fit-content;" onclick="openAddModal()">
                    <i class="bi bi-plus-lg me-1"></i>إضافة
                </button>
            </div>
        </div>
        <?php endif; ?>
        
        <?php foreach ($captains as $c): ?>
        <div class="col-12">
            <div class="card">
                <div class="card-body p-3">
                    <div class="d-flex gap-3">
                        <div class="avatar-circle">
                            <i class="bi bi-person"></i>
                        </div>
                        <div class="flex-grow-1">
                            <div class="d-flex justify-content-between">
                                <h6 class="mb-1"><?php echo e($c['name']); ?></h6>
                                <span class="badge bg-<?php echo $c['status'] == 'active' ? 'success' : 'secondary'; ?>">
                                    <span class="captain-status status-<?php echo $c['status']; ?>"></span>
                                    <?php echo $c['status'] == 'active' ? 'نشط' : 'غير نشط'; ?>
                                </span>
                            </div>
                            <div class="small text-muted mb-1">
                                <i class="bi bi-telephone me-1"></i><?php echo e($c['phone']); ?>
                            </div>
                            <div class="small text-muted mb-2">
                                <i class="bi bi-truck me-1"></i><?php echo e($c['vehicle_info'] ?: 'لا توجد مركبة'); ?>
                            </div>
                            <div class="d-flex gap-2">
                                <span class="badge bg-info"><?php echo $c['orders_count']; ?> طلب</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="d-flex gap-2 mt-3">
                        <form method="POST" class="flex-grow-1">
                            <input type="hidden" name="id" value="<?php echo $c['id']; ?>">
                            <button type="submit" name="toggle" class="btn btn-sm w-100 <?php echo $c['status'] == 'active' ? 'btn-warning' : 'btn-success'; ?>">
                                <i class="bi bi-<?php echo $c['status'] == 'active' ? 'pause' : 'play'; ?> me-1"></i>
                                <?php echo $c['status'] == 'active' ? 'تعطيل' : 'تفعيل'; ?>
                            </button>
                        </form>
                        <button class="btn btn-sm btn-warning" onclick="editCaptain(<?php echo $c['id']; ?>)">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <form method="POST" class="d-inline" onsubmit="return confirm('تأكيد حذف الكابتن؟')">
                            <input type="hidden" name="id" value="<?php echo $c['id']; ?>">
                            <button type="submit" name="delete" class="btn btn-sm btn-danger">
                                <i class="bi bi-trash"></i>
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- Desktop Table -->
    <div class="card d-none d-md-block">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>الاسم</th>
                        <th>رقم الهاتف</th>
                        <th>المركبة</th>
                        <th>الطلبات</th>
                        <th>الحالة</th>
                        <th>تاريخ الإضافة</th>
                        <th>الإجراءات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($captains)): ?>
                    <tr>
                        <td colspan="8" class="text-center py-5">
                            <i class="bi bi-person-badge display-4 text-muted d-block mb-3"></i>
                            <h6>لا توجد كباتن</h6>
                            <button class="btn btn-primary mt-2" onclick="openAddModal()">
                                <i class="bi bi-plus-lg me-1"></i>إضافة كابتن
                            </button>
                        </td>
                    </tr>
                    <?php endif; ?>
                    
                    <?php $i = 1; foreach ($captains as $c): ?>
                    <tr>
                        <td><?php echo $i++; ?></td>
                        <td><strong><?php echo e($c['name']); ?></strong></td>
                        <td dir="ltr"><?php echo e($c['phone']); ?></td>
                        <td><?php echo e($c['vehicle_info'] ?: '-'); ?></td>
                        <td><span class="badge bg-info"><?php echo $c['orders_count']; ?></span></td>
                        <td>
                            <span class="badge bg-<?php echo $c['status'] == 'active' ? 'success' : 'secondary'; ?>">
                                <span class="captain-status status-<?php echo $c['status']; ?>"></span>
                                <?php echo $c['status'] == 'active' ? 'نشط' : 'غير نشط'; ?>
                            </span>
                        </td>
                        <td><?php echo date('Y-m-d', strtotime($c['created_at'])); ?></td>
                        <td>
                            <div class="btn-group">
                                <form method="POST" class="d-inline">
                                    <input type="hidden" name="id" value="<?php echo $c['id']; ?>">
                                    <button type="submit" name="toggle" class="btn btn-sm <?php echo $c['status'] == 'active' ? 'btn-warning' : 'btn-success'; ?> btn-icon" title="<?php echo $c['status'] == 'active' ? 'تعطيل' : 'تفعيل'; ?>">
                                        <i class="bi bi-<?php echo $c['status'] == 'active' ? 'pause' : 'play'; ?>"></i>
                                    </button>
                                </form>
                                <button class="btn btn-sm btn-warning btn-icon" onclick="editCaptain(<?php echo $c['id']; ?>)" title="تعديل">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <form method="POST" class="d-inline" onsubmit="return confirm('تأكيد حذف الكابتن؟')">
                                    <input type="hidden" name="id" value="<?php echo $c['id']; ?>">
                                    <button type="submit" name="delete" class="btn btn-sm btn-danger btn-icon" title="حذف">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- مودال إضافة كابتن -->
<div class="modal fade" id="addModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">إضافة كابتن جديد</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="text" class="form-control mb-2" name="name" placeholder="اسم الكابتن" required>
                    <input type="tel" class="form-control mb-2" name="phone" placeholder="رقم الهاتف" required dir="ltr">
                    <input type="password" class="form-control mb-2" name="password" placeholder="كلمة المرور" required>
                    <input type="text" class="form-control mb-2" name="vehicle" placeholder="معلومات المركبة (نوع ورقم)">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" name="add" class="btn btn-primary">إضافة</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- مودال تعديل كابتن -->
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">تعديل الكابتن</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="id" id="edit_id">
                <div class="modal-body">
                    <input type="text" class="form-control mb-2" name="name" id="edit_name" placeholder="اسم الكابتن" required>
                    <input type="tel" class="form-control mb-2" name="phone" id="edit_phone" placeholder="رقم الهاتف" required dir="ltr">
                    <input type="password" class="form-control mb-2" name="password" placeholder="كلمة المرور (اتركه فارغاً إذا لم ترد التغيير)">
                    <input type="text" class="form-control mb-2" name="vehicle" id="edit_vehicle" placeholder="معلومات المركبة">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" name="edit" class="btn btn-primary">حفظ التغييرات</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function openAddModal() {
    new bootstrap.Modal(document.getElementById('addModal')).show();
}

function editCaptain(id) {
    fetch('captains.php?get_captain=' + id)
        .then(response => response.json())
        .then(data => {
            document.getElementById('edit_id').value = data.id;
            document.getElementById('edit_name').value = data.name;
            document.getElementById('edit_phone').value = data.phone;
            document.getElementById('edit_vehicle').value = data.vehicle_info || '';
            new bootstrap.Modal(document.getElementById('editModal')).show();
        })
        .catch(error => {
            console.error('Error:', error);
            alert('حدث خطأ في تحميل بيانات الكابتن');
        });
}
</script>

<?php include 'includes/footer.php'; ?>