<?php
/**
 * kelola_rute_kapal.php - Halaman Kelola Rute Kapal (Supir)
 * DIPERBAIKI - Semua logika proses di awal sebelum output HTML
 */

// ============================================
// SESSION START
// ============================================
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ============================================
// PROSES FORM SEBELUM OUTPUT HTML
// ============================================

// ============================================
// KONEKSI DATABASE - GUNAKAN PDO DARI CONTROLLER
// ============================================
if (isset($this->pdo) && $this->pdo instanceof PDO) {
    $db = $this->pdo;
} else {
    global $pdo;
    if (isset($pdo) && $pdo instanceof PDO) {
        $db = $pdo;
    } else {
        try {
            $host = 'localhost';
            $username = 'root';
            $password = '';
            $possibleDatabases = ['platform_kapal_samosir', 'reservasi_kapal_wisata', 'reservasi_kapal'];
            $connected = false;
            
            foreach ($possibleDatabases as $dbName) {
                try {
                    $db = new PDO("mysql:host=$host;dbname=$dbName;charset=utf8mb4", $username, $password);
                    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
                    $connected = true;
                    break;
                } catch (PDOException $e) {
                    continue;
                }
            }
            
            if (!$connected) {
                throw new Exception("Tidak dapat terhubung ke database");
            }
        } catch (Exception $e) {
            die("❌ Koneksi database gagal: " . $e->getMessage());
        }
    }
}

$supir_id = $_SESSION['user_id'] ?? 0;
$supir_nama = $_SESSION['nama'] ?? 'Supir';

// ============================================
// PROSES TAMBAH RUTE
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['tambah_rute'])) {
    $kapal_id = isset($_POST['kapal_id']) ? (int)$_POST['kapal_id'] : 0;
    $asal = trim($_POST['asal'] ?? '');
    $tujuan = trim($_POST['tujuan'] ?? '');
    $harga = isset($_POST['harga']) ? (int)$_POST['harga'] : 0;
    $destinasi = isset($_POST['destinasi']) ? $_POST['destinasi'] : [];
    
    $errors = [];
    if ($kapal_id <= 0) $errors[] = "Pilih kapal terlebih dahulu.";
    if (empty($asal)) $errors[] = "Lokasi asal harus diisi.";
    if (empty($tujuan)) $errors[] = "Tujuan harus diisi.";
    if ($harga <= 0) $errors[] = "Harga harus diisi dengan benar.";
    
    if (!empty($errors)) {
        $_SESSION['flash_error'] = implode("<br>", $errors);
        header("Location: ?page=supir&action=kelolaRuteKapal");
        exit;
    }
    
    $destinasi_clean = array_filter($destinasi, function($d) { return !empty(trim($d)); });
    
    try {
        $stmt = $db->prepare("SELECT id FROM kapal WHERE id = ? AND pemilik_id = ?");
        $stmt->execute([$kapal_id, $supir_id]);
        if (!$stmt->fetch()) {
            $_SESSION['flash_error'] = "Kapal tidak ditemukan atau bukan milik Anda.";
            header("Location: ?page=supir&action=kelolaRuteKapal");
            exit;
        }
        
        $all_tujuan = array_merge([$tujuan], $destinasi_clean);
        $rute_string = $asal . ' → ' . implode(' → ', $all_tujuan);
        
        $stmt = $db->prepare("
            INSERT INTO kapal_rute (kapal_id, asal, tujuan, harga_jual, created_at) 
            VALUES (?, ?, ?, ?, NOW())
        ");
        $stmt->execute([$kapal_id, $asal, $rute_string, $harga]);
        
        $_SESSION['flash_success'] = "✅ Rute wisata berhasil ditambahkan!";
        
    } catch (Exception $e) {
        $_SESSION['flash_error'] = "Gagal menambahkan rute: " . $e->getMessage();
    }
    
    header("Location: ?page=supir&action=kelolaRuteKapal");
    exit;
}

// ============================================
// PROSES UPDATE RUTE
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_rute'])) {
    $rute_id = isset($_POST['rute_id']) ? (int)$_POST['rute_id'] : 0;
    $kapal_id = isset($_POST['kapal_id']) ? (int)$_POST['kapal_id'] : 0;
    $asal = trim($_POST['asal'] ?? '');
    $tujuan = trim($_POST['tujuan'] ?? '');
    $harga = isset($_POST['harga']) ? (int)$_POST['harga'] : 0;
    $destinasi = isset($_POST['destinasi']) ? $_POST['destinasi'] : [];
    
    $errors = [];
    if ($rute_id <= 0) $errors[] = "ID rute tidak valid.";
    if ($kapal_id <= 0) $errors[] = "Pilih kapal terlebih dahulu.";
    if (empty($asal)) $errors[] = "Lokasi asal harus diisi.";
    if (empty($tujuan)) $errors[] = "Tujuan harus diisi.";
    if ($harga <= 0) $errors[] = "Harga harus diisi dengan benar.";
    
    if (!empty($errors)) {
        $_SESSION['flash_error'] = implode("<br>", $errors);
        header("Location: ?page=supir&action=kelolaRuteKapal");
        exit;
    }
    
    $destinasi_clean = array_filter($destinasi, function($d) { return !empty(trim($d)); });
    
    try {
        $stmt = $db->prepare("
            SELECT r.id FROM kapal_rute r 
            JOIN kapal k ON r.kapal_id = k.id 
            WHERE r.id = ? AND k.pemilik_id = ?
        ");
        $stmt->execute([$rute_id, $supir_id]);
        if (!$stmt->fetch()) {
            $_SESSION['flash_error'] = "Rute tidak ditemukan atau bukan milik Anda.";
            header("Location: ?page=supir&action=kelolaRuteKapal");
            exit;
        }
        
        $all_tujuan = array_merge([$tujuan], $destinasi_clean);
        $rute_string = $asal . ' → ' . implode(' → ', $all_tujuan);
        
        $stmt = $db->prepare("
            UPDATE kapal_rute 
            SET kapal_id = ?, asal = ?, tujuan = ?, harga_jual = ?, updated_at = NOW()
            WHERE id = ?
        ");
        $stmt->execute([$kapal_id, $asal, $rute_string, $harga, $rute_id]);
        
        $_SESSION['flash_success'] = "✅ Rute wisata berhasil diperbarui!";
        
    } catch (Exception $e) {
        $_SESSION['flash_error'] = "Gagal memperbarui rute: " . $e->getMessage();
    }
    
    header("Location: ?page=supir&action=kelolaRuteKapal");
    exit;
}

// ============================================
// PROSES HAPUS RUTE
// ============================================
if (isset($_GET['action']) && $_GET['action'] === 'hapus' && isset($_GET['id'])) {
    $rute_id = (int)$_GET['id'];
    
    try {
        $stmt = $db->prepare("
            DELETE r FROM kapal_rute r 
            JOIN kapal k ON r.kapal_id = k.id 
            WHERE r.id = ? AND k.pemilik_id = ?
        ");
        $stmt->execute([$rute_id, $supir_id]);
        
        if ($stmt->rowCount() > 0) {
            $_SESSION['flash_success'] = "✅ Rute wisata berhasil dihapus!";
        } else {
            $_SESSION['flash_error'] = "Rute tidak ditemukan atau bukan milik Anda.";
        }
        
    } catch (Exception $e) {
        $_SESSION['flash_error'] = "Gagal menghapus rute: " . $e->getMessage();
    }
    
    header("Location: ?page=supir&action=kelolaRuteKapal");
    exit;
}

// ============================================
// PROSES EDIT RUTE (TAMPILKAN FORM EDIT)
// ============================================
$editData = null;
if (isset($_GET['action']) && $_GET['action'] === 'edit' && isset($_GET['id'])) {
    $rute_id = (int)$_GET['id'];
    
    try {
        $stmt = $db->prepare("
            SELECT r.*, k.nama_kapal 
            FROM kapal_rute r 
            JOIN kapal k ON r.kapal_id = k.id 
            WHERE r.id = ? AND k.pemilik_id = ?
        ");
        $stmt->execute([$rute_id, $supir_id]);
        $editData = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$editData) {
            $_SESSION['flash_error'] = "Rute tidak ditemukan.";
            header("Location: ?page=supir&action=kelolaRuteKapal");
            exit;
        }
        
        if (!empty($editData['tujuan'])) {
            $tujuan_parts = explode(' → ', $editData['tujuan']);
            $editData['tujuan_utama'] = $tujuan_parts[0] ?? '';
            $editData['destinasi_tambahan'] = array_slice($tujuan_parts, 1);
        } else {
            $editData['tujuan_utama'] = '';
            $editData['destinasi_tambahan'] = [];
        }
        
    } catch (Exception $e) {
        $_SESSION['flash_error'] = "Gagal mengambil data rute.";
        header("Location: ?page=supir&action=kelolaRuteKapal");
        exit;
    }
}

// ============================================
// AMBIL DATA KAPAL & RUTE
// ============================================
$kapalList = [];
try {
    $stmt = $db->prepare("
        SELECT id, nama_kapal FROM kapal 
        WHERE pemilik_id = ? AND status_verifikasi = 'verified'
        ORDER BY nama_kapal ASC
    ");
    $stmt->execute([$supir_id]);
    $kapalList = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $kapalList = [];
}

$kapalRute = [];
try {
    $stmt = $db->prepare("
        SELECT r.*, k.nama_kapal 
        FROM kapal_rute r 
        JOIN kapal k ON r.kapal_id = k.id 
        WHERE k.pemilik_id = ? 
        ORDER BY r.created_at DESC
    ");
    $stmt->execute([$supir_id]);
    $kapalRute = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $kapalRute = [];
}

// ============================================
// AMBIL PESANAN MASUK UNTUK BADGE
// ============================================
$pesananMasuk = 0;
try {
    $stmt = $db->prepare("
        SELECT COUNT(*) as total FROM pesanan p 
        JOIN kapal k ON p.kapal_id = k.id 
        WHERE k.pemilik_id = ? AND p.status_pesanan = 'pending'
    ");
    $stmt->execute([$supir_id]);
    $pesananMasuk = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
} catch (Exception $e) {
    $pesananMasuk = 0;
}

// ============================================
// INCLUDE HEADER SETELAH SEMUA PROSES
// ============================================
$activeMenu = 'kelolaRuteKapal';
$pageTitle = 'Kelola Rute - Supir';
include __DIR__ . '/../layouts/header.php';
?>

<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">
        <!-- HEADER -->
        <div class="content-header">
            <div>
                <h2><i class="fas fa-route" style="color:#2b6cb0;"></i> Kelola Rute Wisata</h2>
                <p>Atur rute perjalanan wisata dengan <strong>multi-tujuan</strong> dan <strong>harga per rute</strong>.</p>
                <p style="font-size:0.85rem; color:#718096; margin-top:0.2rem;">
                    <i class="fas fa-info-circle"></i> Total: <strong><?= count($kapalRute) ?></strong> rute terdaftar
                </p>
            </div>
            <button class="btn btn-primary" onclick="toggleForm()">
                <i class="fas fa-plus-circle"></i> Tambah Rute
            </button>
        </div>

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

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

        <!-- FORM TAMBAH/EDIT RUTE -->
        <div id="formTambah" style="display:none;">
            <div class="form-card">
                <div style="display:flex; justify-content:space-between; align-items:center;">
                    <div class="form-title">
                        <i class="fas fa-plus-circle" style="color:#2b6cb0;"></i> 
                        <?= isset($editData) ? 'Edit Rute Wisata' : 'Tambah Rute Wisata' ?>
                    </div>
                    <button class="form-close-btn" onclick="toggleForm()">&times;</button>
                </div>
                <p style="color:#718096; font-size:0.9rem; margin:0.3rem 0 0.5rem;">
                    <?= isset($editData) ? 'Perbarui data rute wisata.' : 'Tambahkan rute perjalanan wisata dengan multi-tujuan.' ?>
                </p>
                
                <form method="POST" action="?page=supir&action=kelolaRuteKapal" id="formRute">
                    <?php if (isset($editData)): ?>
                        <input type="hidden" name="update_rute" value="1">
                        <input type="hidden" name="rute_id" value="<?= $editData['id'] ?>">
                    <?php else: ?>
                        <input type="hidden" name="tambah_rute" value="1">
                    <?php endif; ?>
                    
                    <div class="form-grid">
                        <div class="form-group">
                            <label>Pilih Kapal <span class="required">*</span></label>
                            <select name="kapal_id" required>
                                <option value="">-- Pilih Kapal --</option>
                                <?php foreach($kapalList as $k): ?>
                                    <option value="<?= $k['id'] ?>" <?= isset($editData) && $editData['kapal_id'] == $k['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($k['nama_kapal']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <?php if(empty($kapalList)): ?>
                                <small style="color:#ef4444; display:block; margin-top:0.2rem;">
                                    <i class="fas fa-exclamation-circle"></i> Belum ada kapal terverifikasi. 
                                    <a href="?page=supir&action=kelolaKapal" style="color:#2b6cb0;">Daftarkan kapal</a> terlebih dahulu.
                                </small>
                            <?php endif; ?>
                        </div>
                        <div class="form-group">
                            <label>Lokasi Asal <span class="required">*</span></label>
                            <input type="text" name="asal" placeholder="Contoh: Onanrunggu" 
                                   value="<?= isset($editData) ? htmlspecialchars($editData['asal'] ?? '') : '' ?>" required>
                        </div>
                        <div class="form-group">
                            <label>Tujuan Utama <span class="required">*</span></label>
                            <input type="text" name="tujuan" placeholder="Contoh: Situmurun" 
                                   value="<?= isset($editData) ? htmlspecialchars($editData['tujuan_utama'] ?? '') : '' ?>" required>
                            <small style="color:#718096; font-size:0.7rem;">
                                <i class="fas fa-info-circle"></i> Destinasi utama yang wajib dikunjungi
                            </small>
                        </div>
                        <div class="form-group">
                            <label>Harga Rute (Rp) <span class="required">*</span></label>
                            <input type="number" name="harga" min="1000" step="1000" placeholder="Contoh: 500000" 
                                   value="<?= isset($editData) ? $editData['harga_jual'] ?? '' : '' ?>" required>
                            <small style="color:#718096; font-size:0.7rem;">
                                <i class="fas fa-info-circle"></i> Harga perjalanan sesuai rute ini
                            </small>
                        </div>
                    </div>

                    <!-- MULTI DESTINASI (OPSIONAL) -->
                    <div class="form-group" style="margin-top:0.5rem;">
                        <label>
                            <i class="fas fa-map-pin" style="color:#2b6cb0;"></i> Destinasi Tambahan 
                            <span class="optional">(Opsional)</span>
                        </label>
                        <p style="color:#718096; font-size:0.8rem; margin-bottom:0.5rem;">
                            <i class="fas fa-info-circle"></i> Tambahkan destinasi wisata tambahan jika rute memiliki lebih dari satu titik.
                            <strong>Bisa dikosongkan.</strong>
                        </p>
                        
                        <div class="destinasi-container" id="destinasiContainer">
                            <div class="destinasi-item">
                                <span class="dest-number">#1</span>
                                <input type="text" name="destinasi[]" placeholder="Contoh: Tomok (opsional)"
                                       value="<?= isset($editData) && isset($editData['destinasi_tambahan'][0]) ? htmlspecialchars($editData['destinasi_tambahan'][0]) : '' ?>">
                                <button type="button" class="btn-remove" onclick="removeDestinasi(this)" disabled>
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                            <?php if(isset($editData) && isset($editData['destinasi_tambahan']) && count($editData['destinasi_tambahan']) > 1): ?>
                                <?php for($i = 1; $i < count($editData['destinasi_tambahan']); $i++): ?>
                                    <div class="destinasi-item">
                                        <span class="dest-number">#<?= $i + 1 ?></span>
                                        <input type="text" name="destinasi[]" placeholder="Contoh: Destinasi <?= $i + 1 ?>" 
                                               value="<?= htmlspecialchars($editData['destinasi_tambahan'][$i]) ?>">
                                        <button type="button" class="btn-remove" onclick="removeDestinasi(this)">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </div>
                                <?php endfor; ?>
                            <?php endif; ?>
                        </div>
                        
                        <div style="display:flex; gap:0.5rem; margin-top:0.5rem; flex-wrap:wrap;">
                            <button type="button" class="btn btn-sm btn-success" onclick="addDestinasi()">
                                <i class="fas fa-plus"></i> Tambah Destinasi
                            </button>
                            <button type="button" class="btn btn-sm btn-secondary" onclick="addContohDestinasi()">
                                <i class="fas fa-sync"></i> Contoh Destinasi
                            </button>
                        </div>
                        
                        <div class="destinasi-info" id="destinasiInfo">
                            <i class="fas fa-info-circle"></i>
                            <span id="destinasiCount"><?= isset($editData) && isset($editData['destinasi_tambahan']) ? count($editData['destinasi_tambahan']) : 1 ?></span> destinasi tambahan (opsional)
                        </div>
                    </div>
                    
                    <div class="form-actions">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> <?= isset($editData) ? 'Update Rute' : 'Simpan Rute' ?>
                        </button>
                        <?php if (isset($editData)): ?>
                            <a href="?page=supir&action=kelolaRuteKapal" class="btn btn-secondary">
                                <i class="fas fa-times"></i> Batal
                            </a>
                        <?php else: ?>
                            <button type="button" class="btn btn-secondary" onclick="toggleForm()">Batal</button>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>

        <!-- DAFTAR RUTE -->
        <?php if (empty($kapalRute)): ?>
            <div class="table-wrapper">
                <div class="empty-state">
                    <span class="empty-icon">🗺️</span>
                    <h3>Belum Ada Rute Wisata</h3>
                    <p>Klik tombol <strong>"Tambah Rute"</strong> untuk menambahkan rute perjalanan wisata.</p>
                </div>
            </div>
        <?php else: ?>
            <div class="table-wrapper">
                <div class="table-header">
                    <h3><i class="fas fa-list"></i> Daftar Rute Wisata</h3>
                    <span class="table-count">Total: <?= count($kapalRute) ?> rute</span>
                </div>
                <table>
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Kapal</th>
                            <th>Rute Perjalanan</th>
                            <th>Harga</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($kapalRute as $i => $r): ?>
                            <tr>
                                <td><?= $i + 1 ?></td>
                                <td><strong><?= htmlspecialchars($r['nama_kapal'] ?? '-') ?></strong></td>
                                <td>
                                    <div style="display:flex; flex-wrap:wrap; align-items:center; gap:0.2rem;">
                                        <span class="dest-badge" style="background:#dbeafe; border-color:#93c5fd;">
                                            <i class="fas fa-flag-checkered"></i> <?= htmlspecialchars($r['asal'] ?? '-') ?>
                                        </span>
                                        <?php 
                                        if (!empty($r['tujuan'])) {
                                            $rute_parts = explode(' → ', $r['tujuan']);
                                            foreach($rute_parts as $dest): 
                                        ?>
                                                <span class="rute-arrow"><i class="fas fa-arrow-right"></i></span>
                                                <span class="dest-badge">
                                                    <i class="fas fa-map-pin"></i> <?= htmlspecialchars($dest) ?>
                                                </span>
                                        <?php 
                                            endforeach; 
                                        } else { 
                                        ?>
                                            <span class="rute-arrow"><i class="fas fa-arrow-right"></i></span>
                                            <span class="dest-badge">
                                                <i class="fas fa-map-pin"></i> -
                                            </span>
                                        <?php } ?>
                                    </div>
                                    <?php if(strpos($r['tujuan'] ?? '', ' → ') !== false): ?>
                                        <br>
                                        <small style="color:#718096; font-size:0.65rem;">
                                            <i class="fas fa-location-dot"></i> <?= substr_count($r['tujuan'] ?? '', ' → ') + 1 ?> titik destinasi
                                        </small>
                                    <?php endif; ?>
                                </td>
                                <td style="font-weight:700; color:#2b6cb0;">
                                    Rp <?= number_format($r['harga_jual'] ?? 0, 0, ',', '.') ?>
                                </td>
                                <td>
                                    <div class="action-group">
                                        <a href="?page=supir&action=kelolaRuteKapal&action=edit&id=<?= $r['id'] ?>" class="btn btn-sm btn-warning" title="Edit Rute">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <a href="?page=supir&action=kelolaRuteKapal&action=hapus&id=<?= $r['id'] ?>" 
                                           class="btn btn-sm btn-danger" 
                                           onclick="return confirm('Yakin ingin menghapus rute ini?')" 
                                           title="Hapus Rute">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </main>
</div>

<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 addDestinasi() {
    const container = document.getElementById('destinasiContainer');
    const items = container.querySelectorAll('.destinasi-item');
    
    const newItem = document.createElement('div');
    newItem.className = 'destinasi-item';
    newItem.innerHTML = `
        <span class="dest-number">#${items.length + 1}</span>
        <input type="text" name="destinasi[]" placeholder="Contoh: Destinasi ${items.length + 1} (opsional)">
        <button type="button" class="btn-remove" onclick="removeDestinasi(this)">
            <i class="fas fa-times"></i>
        </button>
    `;
    container.appendChild(newItem);
    updateDestinasiInfo();
}

function removeDestinasi(button) {
    const item = button.closest('.destinasi-item');
    const container = document.getElementById('destinasiContainer');
    const items = container.querySelectorAll('.destinasi-item');
    
    if (items.length <= 1) {
        const input = item.querySelector('input');
        if (input) {
            input.value = '';
            input.placeholder = 'Kosongkan jika tidak perlu';
        }
        return;
    }
    
    item.remove();
    updateDestinasiNumbers();
    updateDestinasiInfo();
}

function updateDestinasiNumbers() {
    const items = document.querySelectorAll('.destinasi-item');
    items.forEach((item, index) => {
        const number = item.querySelector('.dest-number');
        if (number) {
            number.textContent = `#${index + 1}`;
        }
        const input = item.querySelector('input');
        if (input) {
            input.placeholder = `Contoh: Destinasi ${index + 1} (opsional)`;
        }
        const removeBtn = item.querySelector('.btn-remove');
        if (removeBtn) {
            removeBtn.disabled = items.length <= 1;
        }
    });
}

function updateDestinasiInfo() {
    const items = document.querySelectorAll('.destinasi-item');
    const count = items.length;
    const info = document.getElementById('destinasiCount');
    if (info) {
        info.textContent = count;
    }
}

function addContohDestinasi() {
    const contoh = ['Tomok', 'Simanindo', 'Tuktuk', 'Pulau Samosir', 'Hot Spring'];
    const container = document.getElementById('destinasiContainer');
    const items = container.querySelectorAll('.destinasi-item');
    const existingValues = [];
    
    items.forEach(item => {
        const input = item.querySelector('input');
        if (input && input.value) {
            existingValues.push(input.value.trim().toLowerCase());
        }
    });
    
    let added = 0;
    for (let dest of contoh) {
        if (!existingValues.includes(dest.toLowerCase())) {
            const newItem = document.createElement('div');
            newItem.className = 'destinasi-item';
            const newIndex = items.length + added + 1;
            newItem.innerHTML = `
                <span class="dest-number">#${newIndex}</span>
                <input type="text" name="destinasi[]" value="${dest}" placeholder="Contoh: Destinasi ${newIndex} (opsional)">
                <button type="button" class="btn-remove" onclick="removeDestinasi(this)">
                    <i class="fas fa-times"></i>
                </button>
            `;
            container.appendChild(newItem);
            added++;
            if (added >= 3) break;
        }
    }
    
    if (added > 0) {
        updateDestinasiNumbers();
        updateDestinasiInfo();
    } else {
        alert('Semua contoh destinasi sudah ada di daftar!');
    }
}

document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.alert').forEach(function(alert) {
        setTimeout(function() {
            alert.style.transition = 'all 0.5s ease';
            alert.style.opacity = '0';
            alert.style.transform = 'translateY(-10px)';
            setTimeout(function() {
                alert.style.display = 'none';
            }, 500);
        }, 5000);
    });
    
    <?php if (isset($editData)): ?>
        toggleForm();
    <?php endif; ?>
    
    updateDestinasiInfo();
});
</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: 0;
    display: flex;
    align-items: center;
    gap: 0.8rem;
}

.content-header h2 i {
    color: #2b6cb0;
}

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

.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;
    animation: slideDown 0.3s 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: 1.2rem;
    cursor: pointer;
    color: inherit;
    opacity: 0.6;
    padding: 0 4px;
    line-height: 1;
}

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

@keyframes slideDown {
    from { opacity: 0; transform: translateY(-10px); }
    to { opacity: 1; transform: translateY(0); }
}

.btn {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.6rem 1.2rem;
    border: none;
    border-radius: 8px;
    font-weight: 600;
    font-size: 0.85rem;
    cursor: pointer;
    transition: all 0.3s ease;
    text-decoration: none;
    font-family: inherit;
}

.btn:hover {
    transform: translateY(-2px);
    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-success { background: #22c55e; color: #fff; }
.btn-success:hover { background: #16a34a; color: #fff; }
.btn-danger { background: #ef4444; color: #fff; }
.btn-danger:hover { background: #dc2626; color: #fff; }
.btn-warning { background: #f59e0b; color: #fff; }
.btn-warning:hover { background: #d97706; color: #fff; }
.btn-secondary { background: #e2e8f0; color: #4a5568; }
.btn-secondary:hover { background: #cbd5e0; color: #1a202c; }
.btn-sm { padding: 0.3rem 0.8rem; font-size: 0.75rem; }

.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);
    margin-bottom: 1.5rem;
}

.form-title {
    font-size: 1.1rem;
    font-weight: 700;
    color: #1a202c;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

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

.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 .optional { color: #94a3b8; font-size: 0.7rem; font-weight: 400; margin-left: 0.2rem; }

.form-group input,
.form-group select {
    width: 100%;
    padding: 0.5rem 0.7rem;
    border: 1.5px solid #e2e8f0;
    border-radius: 8px;
    font-size: 0.9rem;
    transition: all 0.3s ease;
    background: #f7fafc;
    font-family: inherit;
}

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

.form-actions {
    display: flex;
    gap: 0.8rem;
    margin-top: 1rem;
    padding-top: 1rem;
    border-top: 1px solid #e2e8f0;
}

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

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

.destinasi-container {
    background: #f7fafc;
    border-radius: 8px;
    padding: 0.8rem;
    border: 1px solid #e2e8f0;
    margin-top: 0.5rem;
}

.destinasi-item {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin-bottom: 0.5rem;
    padding: 0.3rem 0.5rem;
    background: #fff;
    border-radius: 6px;
    border: 1px solid #e2e8f0;
}

.destinasi-item:last-child { margin-bottom: 0; }
.destinasi-item .dest-number { font-weight: 700; color: #2b6cb0; min-width: 30px; font-size: 0.8rem; }
.destinasi-item input { flex: 1; padding: 0.4rem 0.6rem; border: 1px solid #e2e8f0; border-radius: 6px; font-size: 0.85rem; background: #fff; }
.destinasi-item input:focus { outline: none; border-color: #2b6cb0; box-shadow: 0 0 0 3px rgba(43,108,176,0.08); }
.destinasi-item .btn-remove { background: #fee2e2; color: #991b1b; border: none; border-radius: 6px; padding: 0.2rem 0.5rem; cursor: pointer; transition: all 0.2s; font-size: 0.75rem; }
.destinasi-item .btn-remove:hover { background: #fecaca; }
.destinasi-item .btn-remove:disabled { opacity: 0.3; cursor: not-allowed; }

.destinasi-info {
    display: flex;
    align-items: center;
    gap: 0.3rem;
    font-size: 0.75rem;
    color: #718096;
    margin-top: 0.3rem;
}

.destinasi-info i { color: #2b6cb0; }

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

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

.table-header h3 {
    font-size: 1rem;
    font-weight: 600;
    color: #2d3748;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin: 0;
}

.table-count { font-size: 0.85rem; color: #718096; }

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

.dest-badge {
    display: inline-block;
    background: #ebf8ff;
    color: #2b6cb0;
    padding: 0.1rem 0.5rem;
    border-radius: 4px;
    margin: 0.1rem 0.15rem;
    font-size: 0.75rem;
    border: 1px solid #bee3f8;
}

.dest-badge i { font-size: 0.6rem; margin-right: 0.2rem; }

.rute-arrow { color: #2b6cb0; margin: 0 0.2rem; font-size: 0.7rem; }

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

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

.empty-state .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; }

@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; }
    .form-actions { flex-direction: column; }
    .form-actions .btn { width: 100%; justify-content: center; }
    table { font-size: 0.8rem; min-width: 600px; }
    table th, table td { padding: 0.4rem 0.6rem; }
}

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

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