<?php
/**
 * kelola_kapal.php - Halaman Kelola Kapal untuk Supir
 * DIPERBAIKI - Menambahkan tombol Detail dan tampilan lebih informatif
 * DIPERBAIKI - Hapus kapal dengan aman menggunakan tabel kapal_rute
 */

// ============================================
// PASTIKAN KONEKSI DATABASE
// ============================================
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Cari file database.php
$possiblePaths = [
    __DIR__ . '/../../config/database.php',
    __DIR__ . '/../config/database.php',
    __DIR__ . '/config/database.php',
    dirname(__DIR__, 2) . '/config/database.php',
];

$dbFound = false;
foreach ($possiblePaths as $path) {
    if (file_exists($path)) {
        require_once $path;
        if (isset($db) && $db instanceof mysqli) {
            $dbFound = true;
            break;
        }
    }
}

// Jika masih tidak ada, buat koneksi sendiri
if (!$dbFound || !isset($db) || !$db instanceof mysqli) {
    $host = 'localhost';
    $username = 'root';
    $password = '';
    $possibleDatabases = [
        'platform_kapal_samosir',
        'reservasi_kapal_wisata', 
        'reservasi_kapal',
        'kapal_wisata',
        'db_reservasi',
        'reservasi'
    ];
    
    foreach ($possibleDatabases as $dbName) {
        try {
            $db = new mysqli($host, $username, $password, $dbName);
            if (!$db->connect_error) {
                $db->set_charset("utf8mb4");
                break;
            }
        } catch (Exception $e) {
            continue;
        }
    }
}

// Jika masih gagal, tampilkan error
if (!isset($db) || !$db instanceof mysqli) {
    die("❌ Koneksi database gagal! Silakan periksa konfigurasi database.");
}

// ============================================
// AMBIL DATA USER DARI SESSION
// ============================================
$supir_id = $_SESSION['user_id'] ?? 0;
$supir_nama = $_SESSION['nama'] ?? 'Supir';
$supir_no_hp = $_SESSION['no_hp'] ?? '';

// ============================================
// PROSES HAPUS KAPAL LANGSUNG (TANPA REQUEST)
// ============================================
if (isset($_GET['action']) && $_GET['action'] === 'hapus' && isset($_GET['id'])) {
    $kapal_id = (int)$_GET['id'];
    $confirm = isset($_GET['confirm']) ? $_GET['confirm'] : '';
    
    // Cek kepemilikan
    $checkQuery = "SELECT id, nama_kapal FROM kapal WHERE id = ? AND pemilik_id = ?";
    $checkStmt = $db->prepare($checkQuery);
    $checkStmt->bind_param('ii', $kapal_id, $supir_id);
    $checkStmt->execute();
    $checkResult = $checkStmt->get_result();
    
    if ($checkResult->num_rows === 0) {
        $_SESSION['error_message'] = '❌ Kapal tidak ditemukan atau bukan milik Anda!';
        header('Location: ?page=supir&action=kelolaKapal');
        exit;
    }
    
    $kapal = $checkResult->fetch_assoc();
    
    // Jika belum konfirmasi, tampilkan modal konfirmasi
    if ($confirm !== 'yes') {
        $_SESSION['hapus_kapal_id'] = $kapal_id;
        $_SESSION['hapus_kapal_nama'] = $kapal['nama_kapal'];
        header('Location: ?page=supir&action=kelolaKapal&confirm_hapus=1');
        exit;
    }
    
    // Proses hapus - GUNAKAN METODE LANGSUNG TANPA CEK TABEL rute_kapal
    try {
        $db->begin_transaction();
        
        // ==============================================
        // HAPUS DATA TERKAIT - MENGGUNAKAN kapal_rute (BUKAN rute_kapal)
        // ==============================================
        
        // 1. Hapus dari shared_trip_participants (jika ada)
        $checkTable = $db->query("SHOW TABLES LIKE 'shared_trip_participants'");
        if ($checkTable && $checkTable->num_rows > 0) {
            $deleteStmt = $db->prepare("DELETE stp FROM shared_trip_participants stp JOIN shared_trips st ON stp.trip_id = st.id WHERE st.kapal_id = ?");
            $deleteStmt->bind_param('i', $kapal_id);
            $deleteStmt->execute();
        }
        
        // 2. Hapus dari shared_trips (jika ada)
        $checkTable = $db->query("SHOW TABLES LIKE 'shared_trips'");
        if ($checkTable && $checkTable->num_rows > 0) {
            $deleteStmt = $db->prepare("DELETE FROM shared_trips WHERE kapal_id = ?");
            $deleteStmt->bind_param('i', $kapal_id);
            $deleteStmt->execute();
        }
        
        // 3. Hapus dari kapal_rute (BUKAN rute_kapal)
        $checkTable = $db->query("SHOW TABLES LIKE 'kapal_rute'");
        if ($checkTable && $checkTable->num_rows > 0) {
            $deleteStmt = $db->prepare("DELETE FROM kapal_rute WHERE kapal_id = ?");
            $deleteStmt->bind_param('i', $kapal_id);
            $deleteStmt->execute();
        }
        
        // 4. Hapus dari schedules (jika ada)
        $checkTable = $db->query("SHOW TABLES LIKE 'schedules'");
        if ($checkTable && $checkTable->num_rows > 0) {
            $deleteStmt = $db->prepare("DELETE FROM schedules WHERE kapal_id = ?");
            $deleteStmt->bind_param('i', $kapal_id);
            $deleteStmt->execute();
        }
        
        // 5. Hapus dari pesanan (jika ada)
        $checkTable = $db->query("SHOW TABLES LIKE 'pesanan'");
        if ($checkTable && $checkTable->num_rows > 0) {
            $deleteStmt = $db->prepare("DELETE FROM pesanan WHERE kapal_id = ?");
            $deleteStmt->bind_param('i', $kapal_id);
            $deleteStmt->execute();
        }
        
        // 6. Hapus dari request_hapus_kapal (jika ada)
        $checkTable = $db->query("SHOW TABLES LIKE 'request_hapus_kapal'");
        if ($checkTable && $checkTable->num_rows > 0) {
            $deleteStmt = $db->prepare("DELETE FROM request_hapus_kapal WHERE kapal_id = ?");
            $deleteStmt->bind_param('i', $kapal_id);
            $deleteStmt->execute();
        }
        
        // 7. Hapus kapal
        $deleteKapal = $db->prepare("DELETE FROM kapal WHERE id = ? AND pemilik_id = ?");
        $deleteKapal->bind_param('ii', $kapal_id, $supir_id);
        $deleteKapal->execute();
        
        $db->commit();
        
        // Hapus session
        unset($_SESSION['hapus_kapal_id']);
        unset($_SESSION['hapus_kapal_nama']);
        
        $_SESSION['flash_message'] = '✅ Kapal "' . $kapal['nama_kapal'] . '" berhasil dihapus!';
        
    } catch (Exception $e) {
        $db->rollback();
        $_SESSION['error_message'] = '❌ Gagal menghapus kapal: ' . $e->getMessage();
    }
    
    header('Location: ?page=supir&action=kelolaKapal');
    exit;
}

// ============================================
// PROSES TAMBAH KAPAL
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['tambah'])) {
    $nama_kapal = trim($_POST['nama_kapal'] ?? '');
    $nomor_lambung = trim($_POST['nomor_lambung'] ?? '');
    $jenis = trim($_POST['jenis'] ?? '');
    $kapasitas = (int)($_POST['kapasitas'] ?? 0);
    $pelabuhan_asal = trim($_POST['pelabuhan_asal'] ?? '');
    $fasilitas = trim($_POST['fasilitas'] ?? '');
    
    // Validasi
    if (empty($nama_kapal) || empty($jenis) || $kapasitas <= 0 || empty($pelabuhan_asal)) {
        $_SESSION['error_message'] = '❌ Semua field wajib diisi!';
        header('Location: ?page=supir&action=kelolaKapal');
        exit;
    }
    
    // Upload foto
    $foto = '';
    if (isset($_FILES['foto']) && $_FILES['foto']['error'] === 0) {
        $allowed = ['image/jpeg', 'image/png', 'image/jpg', 'image/webp'];
        if (in_array($_FILES['foto']['type'], $allowed)) {
            $foto = time() . '_' . $_FILES['foto']['name'];
            $uploadDir = __DIR__ . '/../../uploads/kapal/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            move_uploaded_file($_FILES['foto']['tmp_name'], $uploadDir . $foto);
        }
    }
    
    // Simpan ke database
    $insertQuery = "INSERT INTO kapal (nama_kapal, nomor_lambung, jenis, kapasitas, pelabuhan_asal, fasilitas, foto, pemilik_id, status_verifikasi, created_at) 
                   VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())";
    $insertStmt = $db->prepare($insertQuery);
    $insertStmt->bind_param(
        'sssisssi',
        $nama_kapal,
        $nomor_lambung,
        $jenis,
        $kapasitas,
        $pelabuhan_asal,
        $fasilitas,
        $foto,
        $supir_id
    );
    
    if ($insertStmt->execute()) {
        $_SESSION['flash_message'] = '✅ Kapal "' . $nama_kapal . '" berhasil didaftarkan! Menunggu verifikasi admin.';
    } else {
        $_SESSION['error_message'] = '❌ Gagal mendaftarkan kapal: ' . $db->error;
    }
    
    header('Location: ?page=supir&action=kelolaKapal');
    exit;
}

// ============================================
// PROSES REQUEST HAPUS KAPAL
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'request_hapus') {
    $kapal_id = isset($_POST['kapal_id']) ? (int)$_POST['kapal_id'] : 0;
    $alasan = isset($_POST['alasan']) ? trim($_POST['alasan']) : '';
    
    if ($kapal_id <= 0) {
        $_SESSION['error_message'] = '❌ Kapal tidak valid!';
        header('Location: ?page=supir&action=kelolaKapal');
        exit;
    }
    
    if (empty($alasan)) {
        $_SESSION['error_message'] = '❌ Alasan penghapusan harus diisi!';
        header('Location: ?page=supir&action=kelolaKapal');
        exit;
    }
    
    // Cek apakah kapal milik supir ini
    $checkQuery = "SELECT id, nama_kapal, jenis, kapasitas FROM kapal WHERE id = ? AND pemilik_id = ?";
    $checkStmt = $db->prepare($checkQuery);
    $checkStmt->bind_param('ii', $kapal_id, $supir_id);
    $checkStmt->execute();
    $checkResult = $checkStmt->get_result();
    
    if ($checkResult->num_rows === 0) {
        $_SESSION['error_message'] = '❌ Kapal tidak ditemukan atau bukan milik Anda!';
        header('Location: ?page=supir&action=kelolaKapal');
        exit;
    }
    
    $kapal = $checkResult->fetch_assoc();
    
    // Cek apakah sudah ada request pending
    $cekRequest = "SELECT id FROM request_hapus_kapal WHERE kapal_id = ? AND hapus_request = 'pending'";
    $cekStmt = $db->prepare($cekRequest);
    $cekStmt->bind_param('i', $kapal_id);
    $cekStmt->execute();
    $cekResult = $cekStmt->get_result();
    
    if ($cekResult->num_rows > 0) {
        $_SESSION['error_message'] = '⚠️ Request hapus untuk kapal ini sudah diajukan, menunggu admin.';
        header('Location: ?page=supir&action=kelolaKapal');
        exit;
    }
    
    // SIMPAN REQUEST KE DATABASE
    $kapal_id_int = (int)$kapal_id;
    $nama_kapal_str = $kapal['nama_kapal'] ?? '';
    $jenis_str = $kapal['jenis'] ?? '';
    $kapasitas_int = (int)($kapal['kapasitas'] ?? 0);
    $pemilik_id_int = (int)$supir_id;
    $pemilik_nama_str = (string)$supir_nama;
    $pemilik_no_hp_str = (string)$supir_no_hp;
    $alasan_str = (string)$alasan;
    
    $insertQuery = "INSERT INTO request_hapus_kapal 
                   (kapal_id, nama_kapal, jenis, kapasitas, pemilik_id, pemilik_nama, pemilik_no_hp, alasan, hapus_request, hapus_request_at) 
                   VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())";
    $insertStmt = $db->prepare($insertQuery);
    $insertStmt->bind_param(
        'ississss', 
        $kapal_id_int, 
        $nama_kapal_str, 
        $jenis_str, 
        $kapasitas_int,
        $pemilik_id_int, 
        $pemilik_nama_str, 
        $pemilik_no_hp_str, 
        $alasan_str
    );
    
    if ($insertStmt->execute()) {
        $_SESSION['flash_message'] = '✅ Request hapus kapal "' . $kapal['nama_kapal'] . '" berhasil diajukan! Menunggu verifikasi admin.';
    } else {
        $_SESSION['error_message'] = '❌ Gagal mengajukan request: ' . $db->error;
    }
    
    header('Location: ?page=supir&action=kelolaKapal');
    exit;
}

// ============================================
// PROSES BATALKAN REQUEST HAPUS
// ============================================
if (isset($_GET['action']) && $_GET['action'] === 'batalkan_request' && isset($_GET['id'])) {
    $request_id = (int)$_GET['id'];
    
    $checkQuery = "SELECT id, kapal_id, nama_kapal FROM request_hapus_kapal 
                   WHERE id = ? AND pemilik_id = ? AND hapus_request = 'pending'";
    $checkStmt = $db->prepare($checkQuery);
    $checkStmt->bind_param('ii', $request_id, $supir_id);
    $checkStmt->execute();
    $checkResult = $checkStmt->get_result();
    
    if ($checkResult->num_rows === 0) {
        $_SESSION['error_message'] = '❌ Request tidak ditemukan atau sudah diproses!';
        header('Location: ?page=supir&action=kelolaKapal');
        exit;
    }
    
    $request = $checkResult->fetch_assoc();
    
    $deleteQuery = "DELETE FROM request_hapus_kapal WHERE id = ?";
    $deleteStmt = $db->prepare($deleteQuery);
    $deleteStmt->bind_param('i', $request_id);
    
    if ($deleteStmt->execute()) {
        $_SESSION['flash_message'] = '✅ Request hapus kapal "' . $request['nama_kapal'] . '" berhasil dibatalkan!';
    } else {
        $_SESSION['error_message'] = '❌ Gagal membatalkan request: ' . $db->error;
    }
    
    header('Location: ?page=supir&action=kelolaKapal');
    exit;
}

// ============================================
// AMBIL DAFTAR KAPAL SUPIR
// ============================================
$kapal = [];
$query = "SELECT k.*, 
          r.id as request_id,
          r.hapus_request as request_status,
          r.alasan as alasan_hapus
          FROM kapal k
          LEFT JOIN request_hapus_kapal r ON k.id = r.kapal_id AND r.hapus_request = 'pending'
          WHERE k.pemilik_id = ? 
          ORDER BY k.created_at DESC";
$stmt = $db->prepare($query);
$stmt->bind_param('i', $supir_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $kapal[] = $row;
}

// ============================================
// CEK APAKAH ADA KONFIRMASI HAPUS
// ============================================
$showConfirmModal = isset($_GET['confirm_hapus']) && isset($_SESSION['hapus_kapal_id']);

// ============================================
// LANJUTKAN KODE HALAMAN
// ============================================
include __DIR__ . '/../layouts/header.php';
$activeMenu = 'kelolaKapal';
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">

<div class="dashboard-wrapper">
    <?php include __DIR__ . '/../layouts/sidebar_supir.php'; ?>

    <main class="main-content">
        <div class="content-header">
            <div>
                <h2><i class="fas fa-ship" style="color:#2b6cb0;"></i> Kelola Kapal</h2>
                <p>Kelola kapal yang sudah Anda daftarkan.</p>
            </div>
            <!-- TOMBOL TAMBAH KAPAL -->
            <button class="btn btn-primary" onclick="toggleForm()">
                <i class="fas fa-plus"></i> Tambah Kapal
            </button>
        </div>

        <?php if(isset($_SESSION['flash_message'])): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                <?= htmlspecialchars($_SESSION['flash_message']) ?>
                <button class="alert-close" onclick="this.parentElement.remove()">&times;</button>
                <?php unset($_SESSION['flash_message']); ?>
            </div>
        <?php endif; ?>

        <?php if(isset($_SESSION['error_message'])): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle"></i>
                <?= htmlspecialchars($_SESSION['error_message']) ?>
                <button class="alert-close" onclick="this.parentElement.remove()">&times;</button>
                <?php unset($_SESSION['error_message']); ?>
            </div>
        <?php endif; ?>

        <!-- FORM TAMBAH KAPAL -->
        <div id="formTambah" style="display:none; margin-bottom:1.5rem;">
            <div class="form-card">
                <div class="form-header">
                    <h3><i class="fas fa-plus-circle"></i> Daftarkan Kapal Baru</h3>
                    <button type="button" class="btn-close-form" onclick="toggleForm()">&times;</button>
                </div>
                <p style="color:#718096; font-size:0.9rem; margin:0.5rem 0 1rem;">
                    Setelah kapal diverifikasi, Anda bisa menambahkan rute di menu Kelola Rute.
                </p>
                <form method="POST" action="" enctype="multipart/form-data">
                    <input type="hidden" name="tambah" value="1">
                    <div class="form-grid">
                        <div class="form-group">
                            <label>Nama Kapal <span class="required">*</span></label>
                            <input type="text" name="nama_kapal" placeholder="Contoh: KM. Bahari" required>
                        </div>
                        <div class="form-group">
                            <label>Nomor Lambung</label>
                            <input type="text" name="nomor_lambung" placeholder="Contoh: KM-001">
                        </div>
                        <div class="form-group">
                            <label>Jenis Kapal <span class="required">*</span></label>
                            <select name="jenis" required>
                                <option value="">-- Pilih --</option>
                                <option value="speedboat">Speedboat</option>
                                <option value="kapal_kayu">Kapal Kayu</option>
                                <option value="ferry">Ferry</option>
                                <option value="kapal_motor">Kapal Motor</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Kapasitas (orang) <span class="required">*</span></label>
                            <input type="number" name="kapasitas" min="1" max="100" placeholder="Jumlah penumpang" required>
                        </div>
                        <div class="form-group">
                            <label>Pelabuhan Asal <span class="required">*</span></label>
                            <input type="text" name="pelabuhan_asal" placeholder="Contoh: Parapat" required>
                        </div>
                        <div class="form-group">
                            <label>Fasilitas</label>
                            <input type="text" name="fasilitas" placeholder="Contoh: AC, TV, Toilet">
                        </div>
                        <div class="form-group" style="grid-column: 1 / -1;">
                            <label>Foto Kapal</label>
                            <input type="file" name="foto" accept="image/*" class="file-input">
                            <small style="color:#a0aec0;">Format JPG, PNG, WebP. Maks 2MB</small>
                        </div>
                    </div>
                    <div class="form-actions">
                        <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Daftarkan Kapal</button>
                        <button type="button" class="btn btn-secondary" onclick="toggleForm()">Batal</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- DAFTAR KAPAL -->
        <?php if(empty($kapal)): ?>
            <div class="empty-state">
                <div class="empty-icon">⛵</div>
                <h3>Belum Ada Kapal</h3>
                <p>Klik tombol <strong>"Tambah Kapal"</strong> untuk mendaftarkan kapal Anda.</p>
            </div>
        <?php else: ?>
            <div class="table-section">
                <div class="table-header">
                    <h3><i class="fas fa-list"></i> Daftar Kapal</h3>
                    <span class="table-count">Total: <?= count($kapal) ?> kapal</span>
                </div>
                <div class="table-wrapper">
                    <table>
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Nama Kapal</th>
                                <th>Asal</th>
                                <th>Jenis</th>
                                <th>Kapasitas</th>
                                <th>Status</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($kapal as $i => $k): 
                                $badge = 'badge-pending';
                                $statusText = '⏳ Menunggu Verifikasi';
                                
                                if($k['status_verifikasi'] == 'verified') {
                                    $badge = 'badge-success';
                                    $statusText = '✅ Terverifikasi';
                                } elseif($k['status_verifikasi'] == 'rejected') {
                                    $badge = 'badge-danger';
                                    $statusText = '❌ Ditolak';
                                }
                                
                                $hasRequest = !empty($k['request_status']) && $k['request_status'] == 'pending';
                                
                                // Cek apakah bisa dihapus (hanya kapal yang belum diverifikasi atau sudah diverifikasi tanpa pesanan aktif)
                                $canDelete = ($k['status_verifikasi'] == 'pending' || $k['status_verifikasi'] == 'rejected');
                            ?>
                                <tr>
                                    <td><?= $i+1 ?></td>
                                    <td>
                                        <strong><?= htmlspecialchars($k['nama_kapal']) ?></strong>
                                        <?php if(!empty($k['nomor_lambung'])): ?>
                                            <br><small style="color:#718096;"><?= htmlspecialchars($k['nomor_lambung']) ?></small>
                                        <?php endif; ?>
                                        <?php if($hasRequest): ?>
                                            <br>
                                            <span class="badge badge-warning" style="margin-top:3px;">
                                                <i class="fas fa-clock"></i> Request Hapus Menunggu
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= htmlspecialchars($k['pelabuhan_asal'] ?? '-') ?></td>
                                    <td><?= ucfirst($k['jenis']) ?></td>
                                    <td><?= $k['kapasitas'] ?> org</td>
                                    <td>
                                        <span class="badge <?= $badge ?>"><?= $statusText ?></span>
                                        <?php if(!empty($k['alasan_hapus'])): ?>
                                            <br>
                                            <small style="color:#718096; font-size:0.65rem;">
                                                Alasan: <?= htmlspecialchars($k['alasan_hapus']) ?>
                                            </small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="action-group">
                                            <!-- TOMBOL DETAIL -->
                                            <a href="?page=supir&action=detailKapal&id=<?= $k['id'] ?>" class="btn btn-sm btn-primary">
                                                <i class="fas fa-eye"></i> Detail
                                            </a>
                                            
                                            <?php if($k['status_verifikasi'] == 'verified'): ?>
                                                <a href="?page=supir&action=kelolaRuteKapal&kapal_id=<?= $k['id'] ?>" class="btn btn-sm btn-info">
                                                    <i class="fas fa-route"></i> Rute
                                                </a>
                                                
                                                <?php if($hasRequest): ?>
                                                    <a href="?page=supir&action=kelolaKapal&action=batalkan_request&id=<?= $k['request_id'] ?>" 
                                                       class="btn btn-sm btn-warning" 
                                                       onclick="return confirm('Yakin ingin membatalkan request hapus kapal ini?')">
                                                        <i class="fas fa-undo"></i> Batalkan
                                                    </a>
                                                    <span class="badge badge-warning">Menunggu Admin</span>
                                                <?php else: ?>
                                                    <button class="btn btn-sm btn-danger" onclick="openRequestHapus(<?= $k['id'] ?>, '<?= htmlspecialchars($k['nama_kapal']) ?>')">
                                                        <i class="fas fa-trash-alt"></i> Request Hapus
                                                    </button>
                                                <?php endif; ?>
                                                
                                            <?php elseif($k['status_verifikasi'] == 'pending'): ?>
                                                <span class="badge badge-warning">Menunggu Verifikasi</span>
                                                <!-- TOMBOL HAPUS LANGSUNG UNTUK KAPAL BELUM VERIFIKASI -->
                                                <a href="?page=supir&action=kelolaKapal&action=hapus&id=<?= $k['id'] ?>&confirm=yes" 
                                                   class="btn btn-sm btn-danger" 
                                                   onclick="return confirm('Yakin ingin menghapus kapal \'<?= htmlspecialchars($k['nama_kapal']) ?>\' secara permanen?')">
                                                    <i class="fas fa-trash"></i> Hapus
                                                </a>
                                            <?php elseif($k['status_verifikasi'] == 'rejected'): ?>
                                                <span class="badge badge-danger">Ditolak</span>
                                                <a href="?page=supir&action=kelolaKapal&action=hapus&id=<?= $k['id'] ?>&confirm=yes" 
                                                   class="btn btn-sm btn-danger" 
                                                   onclick="return confirm('Yakin ingin menghapus kapal \'<?= htmlspecialchars($k['nama_kapal']) ?>\' secara permanen?')">
                                                    <i class="fas fa-trash"></i> Hapus
                                                </a>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endif; ?>
    </main>
</div>

<!-- MODAL REQUEST HAPUS -->
<div class="modal-overlay" id="modalRequestHapus">
    <div class="modal">
        <div class="modal-header">
            <h3><i class="fas fa-trash-alt" style="color:#ef4444;"></i> Request Hapus Kapal</h3>
            <button class="modal-close" onclick="closeRequestHapus()">&times;</button>
        </div>
        <form method="POST" action="">
            <input type="hidden" name="action" value="request_hapus">
            <input type="hidden" name="kapal_id" id="requestKapalId">
            <div class="form-group">
                <label>Kapal</label>
                <p id="requestKapalNama" style="font-weight:600; font-size:1rem; color:#1a202c;"></p>
            </div>
            <div class="form-group">
                <label>Alasan Penghapusan <span class="required">*</span></label>
                <textarea name="alasan" id="requestAlasan" class="form-control" rows="4" placeholder="Masukkan alasan mengapa kapal ini ingin dihapus..." required></textarea>
                <small class="form-hint"><i class="fas fa-info-circle"></i> Alasan akan dikirimkan ke admin untuk ditinjau.</small>
            </div>
            <div class="form-actions">
                <button type="button" class="btn btn-secondary" onclick="closeRequestHapus()">Batal</button>
                <button type="submit" class="btn btn-danger"><i class="fas fa-paper-plane"></i> Kirim Request</button>
            </div>
        </form>
    </div>
</div>

<!-- MODAL KONFIRMASI HAPUS -->
<?php if($showConfirmModal && isset($_SESSION['hapus_kapal_id'])): ?>
<div class="modal-overlay" id="confirmHapusModal" style="display:flex;">
    <div class="modal">
        <div class="modal-header">
            <h3><i class="fas fa-exclamation-triangle" style="color:#ef4444;"></i> Konfirmasi Hapus Kapal</h3>
            <button class="modal-close" onclick="closeConfirmModal()">&times;</button>
        </div>
        <div class="modal-body">
            <p style="font-size:1rem; margin-bottom:1rem;">
                Apakah Anda yakin ingin menghapus kapal 
                <strong>"<?= htmlspecialchars($_SESSION['hapus_kapal_nama'] ?? '') ?>"</strong>?
            </p>
            <div class="alert alert-danger" style="margin-bottom:1rem;">
                <i class="fas fa-exclamation-circle"></i>
                <span>⚠️ Tindakan ini <strong>TIDAK DAPAT DIBATALKAN</strong>. Semua data terkait kapal ini akan dihapus.</span>
            </div>
            <div class="form-actions">
                <button type="button" class="btn btn-secondary" onclick="closeConfirmModal()">Batal</button>
                <a href="?page=supir&action=kelolaKapal&action=hapus&id=<?= $_SESSION['hapus_kapal_id'] ?>&confirm=yes" class="btn btn-danger">
                    <i class="fas fa-trash"></i> Ya, Hapus Kapal
                </a>
            </div>
        </div>
    </div>
</div>
<script>
function closeConfirmModal() {
    document.getElementById('confirmHapusModal').style.display = 'none';
    window.location.href = '?page=supir&action=kelolaKapal';
}
</script>
<?php 
// Hapus session agar tidak muncul lagi saat refresh
unset($_SESSION['hapus_kapal_id']);
unset($_SESSION['hapus_kapal_nama']);
endif; 
?>

<script>
function toggleForm() {
    const form = document.getElementById('formTambah');
    if (form.style.display === 'none' || form.style.display === '') {
        form.style.display = 'block';
        form.scrollIntoView({ behavior: 'smooth', block: 'start' });
    } else {
        form.style.display = 'none';
    }
}

function openRequestHapus(id, nama) {
    document.getElementById('requestKapalId').value = id;
    document.getElementById('requestKapalNama').textContent = nama;
    document.getElementById('modalRequestHapus').classList.add('active');
    document.body.style.overflow = 'hidden';
}

function closeRequestHapus() {
    document.getElementById('modalRequestHapus').classList.remove('active');
    document.body.style.overflow = '';
}

document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeRequestHapus();
        closeConfirmModal();
    }
});

document.getElementById('modalRequestHapus').addEventListener('click', function(e) {
    if (e.target === this) {
        closeRequestHapus();
    }
});

document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.alert').forEach(alert => {
        setTimeout(() => {
            alert.style.transition = 'all 0.5s ease';
            alert.style.opacity = '0';
            alert.style.transform = 'translateY(-10px)';
            setTimeout(() => alert.style.display = 'none', 500);
        }, 5000);
    });
});
</script>

<style>
.dashboard-wrapper {
    display: flex;
    gap: 24px;
    max-width: 1200px;
    margin: 1.5rem auto 0;
    padding: 0 20px;
    width: 100%;
    flex: 1;
    align-items: flex-start;
}

.main-content {
    flex: 1;
    min-width: 0;
    background: #fff;
    border-radius: 14px;
    padding: 1.8rem;
    box-shadow: 0 4px 20px rgba(0,0,0,0.06);
    border: 1px solid #e2e8f0;
}

.content-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.5rem;
    flex-wrap: wrap;
    gap: 12px;
}

.content-header h2 {
    font-size: 1.4rem;
    font-weight: 700;
    color: #1a202c;
    margin-bottom: 0.2rem;
}

.content-header p {
    color: #718096;
    font-size: 0.95rem;
    margin: 0;
}

.btn {
    display: inline-flex;
    align-items: center;
    gap: 0.3rem;
    padding: 0.4rem 1rem;
    border: none;
    border-radius: 6px;
    font-weight: 600;
    font-size: 0.8rem;
    cursor: pointer;
    transition: all 0.3s ease;
    text-decoration: none;
    font-family: inherit;
}

.btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}

.btn-primary { background: #2b6cb0; color: #fff; }
.btn-primary:hover { background: #1a4a7a; color: #fff; }
.btn-secondary { background: #e2e8f0; color: #4a5568; }
.btn-secondary:hover { background: #cbd5e0; color: #1a202c; }
.btn-danger { background: #ef4444; color: #fff; }
.btn-danger:hover { background: #dc2626; color: #fff; }
.btn-warning { background: #f59e0b; color: #1a202c; }
.btn-warning:hover { background: #d97706; color: #1a202c; }
.btn-info { background: #3b82f6; color: #fff; }
.btn-info:hover { background: #2563eb; color: #fff; }
.btn-sm { padding: 0.2rem 0.6rem; font-size: 0.7rem; }

.alert {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 0.8rem 1.2rem;
    border-radius: 10px;
    margin-bottom: 1.2rem;
    border-left: 4px solid transparent;
    transition: all 0.5s ease;
}

.alert-success { background: #d1fae5; color: #065f46; border-left-color: #22c55e; }
.alert-danger { background: #fee2e2; color: #991b1b; border-left-color: #ef4444; }

.alert-close {
    margin-left: auto;
    background: none;
    border: none;
    font-size: 1rem;
    cursor: pointer;
    color: inherit;
    opacity: 0.6;
    padding: 0 4px;
}

.alert-close:hover { opacity: 1; }

.empty-state {
    text-align: center;
    padding: 2.5rem 1.5rem;
    background: #f7fafc;
    border-radius: 12px;
    border: 1px solid #e2e8f0;
}

.empty-icon { font-size: 3.5rem; display: block; margin-bottom: 0.5rem; opacity: 0.5; }
.empty-state h3 { font-size: 1.2rem; font-weight: 700; color: #2d3748; margin-bottom: 0.2rem; }
.empty-state p { color: #718096; font-size: 0.9rem; margin: 0; }

.table-section { margin-top: 0.5rem; }
.table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
    flex-wrap: wrap;
    gap: 0.5rem;
}
.table-header h3 { font-size: 1.05rem; font-weight: 700; color: #2d3748; margin: 0; }
.table-count { font-size: 0.85rem; color: #718096; }

.table-wrapper {
    background: #fff;
    border-radius: 12px;
    overflow-x: auto;
    border: 1px solid #e2e8f0;
}

table {
    width: 100%;
    border-collapse: collapse;
    font-size: 0.9rem;
    min-width: 700px;
}

table th {
    background: #f7fafc;
    color: #4a5568;
    font-weight: 600;
    padding: 0.7rem 1rem;
    text-align: left;
    border-bottom: 2px solid #e2e8f0;
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 0.3px;
}

table td {
    padding: 0.7rem 1rem;
    border-bottom: 1px solid #e2e8f0;
    vertical-align: middle;
}

table tr:hover td { background: #f7fafc; }

.badge {
    display: inline-block;
    padding: 0.15rem 0.6rem;
    border-radius: 20px;
    font-size: 0.65rem;
    font-weight: 600;
    white-space: nowrap;
}

.badge-success { background: #d1fae5; color: #065f46; }
.badge-pending { background: #fef3c7; color: #92400e; }
.badge-danger { background: #fee2e2; color: #991b1b; }
.badge-warning { background: #fef3c7; color: #92400e; }
.badge-secondary { background: #e5e7eb; color: #4b5563; }

.action-group {
    display: flex;
    gap: 0.3rem;
    flex-wrap: wrap;
    align-items: center;
}

.form-card {
    background: #fff;
    border-radius: 12px;
    padding: 1.5rem;
    border: 1px solid #e2e8f0;
    box-shadow: 0 4px 20px rgba(0,0,0,0.04);
}

.form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.form-card h3 { font-size: 1.1rem; font-weight: 700; color: #1a202c; margin: 0; }

.btn-close-form {
    background: none;
    border: none;
    font-size: 1.2rem;
    color: #a0aec0;
    cursor: pointer;
    padding: 0 4px;
    transition: all 0.3s ease;
}

.btn-close-form:hover { color: #1a202c; transform: rotate(90deg); }

.form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 0.8rem;
    margin: 1rem 0;
}

.form-group { margin-bottom: 0.5rem; }
.form-group label { display: block; font-weight: 600; font-size: 0.85rem; color: #4a5568; margin-bottom: 0.2rem; }
.form-group .required { color: #ef4444; }
.form-group input, .form-group select {
    width: 100%;
    padding: 0.5rem 0.7rem;
    border: 1.5px solid #e2e8f0;
    border-radius: 6px;
    font-size: 0.9rem;
    background: #fff;
    transition: all 0.3s ease;
    font-family: inherit;
}

.form-group input:focus, .form-group select:focus {
    outline: none;
    border-color: #2b6cb0;
    box-shadow: 0 0 0 3px rgba(43,108,176,0.08);
}

.form-group .file-input { padding: 0.3rem; border: 1px dashed #cbd5e0; border-radius: 6px; cursor: pointer; }
.form-actions { display: flex; gap: 0.8rem; margin-top: 0.5rem; }

.modal-overlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    z-index: 1000;
    align-items: center;
    justify-content: center;
    padding: 20px;
}

.modal-overlay.active { display: flex; }

.modal {
    background: #fff;
    border-radius: 16px;
    max-width: 500px;
    width: 100%;
    max-height: 90vh;
    overflow-y: auto;
    padding: 1.8rem 2rem;
    animation: modalIn 0.3s ease;
}

@keyframes modalIn {
    from { transform: scale(0.95) translateY(-20px); opacity: 0; }
    to { transform: scale(1) translateY(0); opacity: 1; }
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.2rem;
    padding-bottom: 0.8rem;
    border-bottom: 1px solid #e2e8f0;
}

.modal-header h3 { font-size: 1.1rem; font-weight: 700; color: #1a202c; margin: 0; display: flex; align-items: center; gap: 0.5rem; }

.modal-close {
    background: none;
    border: none;
    font-size: 1.8rem;
    cursor: pointer;
    color: #a0aec0;
    transition: all 0.3s ease;
    line-height: 1;
}

.modal-close:hover { color: #1a202c; }

.form-hint {
    display: block;
    font-size: 0.75rem;
    color: #a0aec0;
    margin-top: 0.2rem;
}

/* Modal Konfirmasi Hapus */
#confirmHapusModal .alert-danger {
    background: #fee2e2;
    color: #991b1b;
    border-left-color: #ef4444;
    display: flex;
    align-items: flex-start;
    gap: 10px;
    padding: 0.8rem 1.2rem;
    border-radius: 10px;
    border-left: 4px solid transparent;
}

#confirmHapusModal .alert-danger i {
    font-size: 1.2rem;
    margin-top: 2px;
}

#confirmHapusModal .alert-danger strong {
    color: #991b1b;
}

@media (max-width: 768px) {
    .dashboard-wrapper { flex-direction: column; padding: 0 12px; margin-top: 1rem; }
    .main-content { padding: 1rem; }
    .content-header { flex-direction: column; align-items: flex-start; }
    .form-grid { grid-template-columns: 1fr; gap: 0.5rem; }
    .table-wrapper table { font-size: 0.8rem; min-width: 600px; }
    .table-wrapper th, .table-wrapper td { padding: 0.4rem 0.6rem; }
    .action-group { flex-direction: column; }
    .action-group .btn { width: 100%; justify-content: center; }
    .modal { padding: 1.2rem; }
}

@media (max-width: 480px) {
    .main-content { padding: 0.8rem; }
    .form-card { padding: 1rem; }
    .btn { font-size: 0.7rem; padding: 0.3rem 0.7rem; }
    .table-wrapper table { font-size: 0.7rem; min-width: 500px; }
    .table-wrapper th, .table-wrapper td { padding: 0.3rem 0.4rem; }
    .badge { font-size: 0.55rem; padding: 0.1rem 0.4rem; }
    .modal { padding: 1rem; }
}
</style>

<?php include __DIR__ . '/../layouts/footer.php'; ?>