<?php
/**
 * tambah_rute.php - Halaman Tambah Rute untuk Supir
 * Support multiple rute (2 rute atau lebih)
 */
include __DIR__ . '/../layouts/header.php';
$activeMenu = 'tambahRute';

// KONEKSI DATABASE
if (!isset($db) || !$db instanceof mysqli) {
    $possiblePaths = [
        __DIR__ . '/../../config/database.php',
        __DIR__ . '/../config/database.php',
        dirname(__DIR__, 2) . '/config/database.php',
    ];
    foreach ($possiblePaths as $path) {
        if (file_exists($path)) {
            require_once $path;
            if (isset($db) && $db instanceof mysqli) {
                break;
            }
        }
    }
}

$supir_id = $_SESSION['user_id'] ?? 0;

// AMBIL DATA KAPAL SUPIR
$kapalList = [];
$query = "SELECT id, nama_kapal FROM kapal WHERE pemilik_id = ? AND status_verifikasi = 'verified' ORDER BY nama_kapal ASC";
$stmt = $db->prepare($query);
$stmt->bind_param('i', $supir_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $kapalList[] = $row;
}

// ============================================
// PROSES TAMBAH RUTE
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['tambah_rute'])) {
    $kapal_id = (int)$_POST['kapal_id'];
    $asal = trim($_POST['asal'] ?? '');
    $tujuan = trim($_POST['tujuan'] ?? '');
    $harga = (int)($_POST['harga'] ?? 0);
    $durasi = (int)($_POST['durasi'] ?? 0);
    $rute_details = isset($_POST['rute_details']) ? $_POST['rute_details'] : [];
    $hari = isset($_POST['hari']) ? $_POST['hari'] : [];
    $waktu_berangkat = isset($_POST['waktu_berangkat']) ? $_POST['waktu_berangkat'] : [];
    
    // Validasi
    if ($kapal_id <= 0 || empty($asal) || empty($tujuan) || $harga <= 0) {
        $_SESSION['error'] = '❌ Semua field wajib diisi!';
        header('Location: ?page=supir&action=tambahRute');
        exit;
    }
    
    // Cek kepemilikan kapal
    $check = $db->query("SELECT id FROM kapal WHERE id = $kapal_id AND pemilik_id = $supir_id");
    if ($check->num_rows === 0) {
        $_SESSION['error'] = '❌ Kapal tidak ditemukan!';
        header('Location: ?page=supir&action=tambahRute');
        exit;
    }
    
    // Mulai transaksi
    $db->begin_transaction();
    
    try {
        // 1. Simpan rute utama
        $insert = "INSERT INTO rute_kapal (kapal_id, asal, tujuan, harga, durasi) VALUES (?, ?, ?, ?, ?)";
        $stmt = $db->prepare($insert);
        $stmt->bind_param('issii', $kapal_id, $asal, $tujuan, $harga, $durasi);
        $stmt->execute();
        $rute_id = $db->insert_id;
        
        // 2. Simpan detail rute (multiple destinations)
        if (!empty($rute_details)) {
            $detailQuery = "INSERT INTO rute_detail (rute_id, tujuan_ke, urutan) VALUES (?, ?, ?)";
            $detailStmt = $db->prepare($detailQuery);
            $urutan = 1;
            foreach ($rute_details as $detail) {
                $tujuan_ke = trim($detail['tujuan'] ?? '');
                if (!empty($tujuan_ke)) {
                    $detailStmt->bind_param('isi', $rute_id, $tujuan_ke, $urutan);
                    $detailStmt->execute();
                    $urutan++;
                }
            }
        }
        
        // 3. Simpan jadwal perjalanan (multiple days)
        if (!empty($hari) && !empty($waktu_berangkat)) {
            $jadwalQuery = "INSERT INTO rute_perjalanan (rute_id, hari, waktu_berangkat) VALUES (?, ?, ?)";
            $jadwalStmt = $db->prepare($jadwalQuery);
            for ($i = 0; $i < count($hari); $i++) {
                if (!empty($hari[$i]) && !empty($waktu_berangkat[$i])) {
                    $jadwalStmt->bind_param('iss', $rute_id, $hari[$i], $waktu_berangkat[$i]);
                    $jadwalStmt->execute();
                }
            }
        }
        
        $db->commit();
        $_SESSION['success'] = '✅ Rute berhasil ditambahkan!';
        header('Location: ?page=supir&action=kelolaRute');
        exit;
        
    } catch (Exception $e) {
        $db->rollback();
        $_SESSION['error'] = '❌ Gagal menambahkan rute: ' . $e->getMessage();
        header('Location: ?page=supir&action=tambahRute');
        exit;
    }
}
?>

<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-route" style="color:#2b6cb0;"></i> Tambah Rute</h2>
                <p>Tambahkan rute perjalanan untuk kapal Anda. Bisa menambahkan <strong>2 rute atau lebih</strong> dalam satu perjalanan.</p>
            </div>
            <div>
                <a href="?page=supir&action=kelolaRute" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> Kembali
                </a>
            </div>
        </div>

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

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

        <div class="form-card">
            <form method="POST" action="" id="formTambahRute">
                <input type="hidden" name="tambah_rute" value="1">
                
                <!-- Pilih Kapal -->
                <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'] ?>"><?= htmlspecialchars($k['nama_kapal']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <?php if(empty($kapalList)): ?>
                        <small style="color:#ef4444;">⚠️ Anda belum memiliki kapal terverifikasi. Daftarkan kapal terlebih dahulu.</small>
                    <?php endif; ?>
                </div>

                <!-- Rute Utama -->
                <div class="form-row">
                    <div class="form-group">
                        <label>Asal <span class="required">*</span></label>
                        <input type="text" name="asal" placeholder="Contoh: Parapat" required>
                    </div>
                    <div class="form-group">
                        <label>Tujuan Akhir <span class="required">*</span></label>
                        <input type="text" name="tujuan" placeholder="Contoh: BAKKARA" required>
                    </div>
                </div>

                <!-- Rute Detail (Multiple Destinations) -->
                <div class="form-group">
                    <label><i class="fas fa-map-pin"></i> Rute Perjalanan (Titik-titik Tujuan)</label>
                    <p style="color:#718096; font-size:0.85rem; margin-bottom:0.5rem;">
                        Tambahkan titik-titik tujuan dalam perjalanan. Minimal 2 rute.
                    </p>
                    <div id="ruteDetailContainer">
                        <div class="rute-detail-item">
                            <div class="rute-detail-input">
                                <span class="rute-number">#1</span>
                                <input type="text" name="rute_details[0][tujuan]" placeholder="Tujuan ke-1" required>
                                <button type="button" class="btn btn-sm btn-danger remove-rute" onclick="removeRute(this)" style="display:none;">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        </div>
                        <div class="rute-detail-item">
                            <div class="rute-detail-input">
                                <span class="rute-number">#2</span>
                                <input type="text" name="rute_details[1][tujuan]" placeholder="Tujuan ke-2" required>
                                <button type="button" class="btn btn-sm btn-danger remove-rute" onclick="removeRute(this)" style="display:none;">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    <button type="button" class="btn btn-sm btn-primary" onclick="addRute()" style="margin-top:0.5rem;">
                        <i class="fas fa-plus"></i> Tambah Rute
                    </button>
                    <small style="color:#718096; display:block; margin-top:0.3rem;">
                        <i class="fas fa-info-circle"></i> Klik "Tambah Rute" untuk menambahkan lebih banyak titik tujuan.
                    </small>
                </div>

                <!-- Harga & Durasi -->
                <div class="form-row">
                    <div class="form-group">
                        <label>Harga (Rp) <span class="required">*</span></label>
                        <input type="number" name="harga" placeholder="Harga per perjalanan" min="0" required>
                        <small style="color:#718096;">Harga per perjalanan untuk rute ini.</small>
                    </div>
                    <div class="form-group">
                        <label>Durasi (jam)</label>
                        <input type="number" name="durasi" placeholder="Estimasi durasi" min="0" step="0.5">
                        <small style="color:#718096;">Estimasi waktu tempuh perjalanan.</small>
                    </div>
                </div>

                <!-- Jadwal Perjalanan -->
                <div class="form-group">
                    <label><i class="fas fa-calendar-alt"></i> Jadwal Perjalanan</label>
                    <p style="color:#718096; font-size:0.85rem; margin-bottom:0.5rem;">
                        Tentukan hari dan waktu keberangkatan.
                    </p>
                    <div id="jadwalContainer">
                        <div class="jadwal-item">
                            <select name="hari[]" required>
                                <option value="">-- Hari --</option>
                                <option value="Senin">Senin</option>
                                <option value="Selasa">Selasa</option>
                                <option value="Rabu">Rabu</option>
                                <option value="Kamis">Kamis</option>
                                <option value="Jumat">Jumat</option>
                                <option value="Sabtu">Sabtu</option>
                                <option value="Minggu">Minggu</option>
                            </select>
                            <input type="time" name="waktu_berangkat[]" required>
                            <button type="button" class="btn btn-sm btn-danger remove-jadwal" onclick="removeJadwal(this)" style="display:none;">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                    <button type="button" class="btn btn-sm btn-primary" onclick="addJadwal()" style="margin-top:0.5rem;">
                        <i class="fas fa-plus"></i> Tambah Jadwal
                    </button>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn btn-primary" <?= empty($kapalList) ? 'disabled' : '' ?>>
                        <i class="fas fa-save"></i> Simpan Rute
                    </button>
                    <a href="?page=supir&action=kelolaRute" class="btn btn-secondary">Batal</a>
                </div>
            </form>
        </div>
    </main>
</div>

<script>
// ============================================
// TAMBAH RUTE DETAIL
// ============================================
let ruteIndex = 2;

function addRute() {
    const container = document.getElementById('ruteDetailContainer');
    const newItem = document.createElement('div');
    newItem.className = 'rute-detail-item';
    newItem.innerHTML = `
        <div class="rute-detail-input">
            <span class="rute-number">#${ruteIndex + 1}</span>
            <input type="text" name="rute_details[${ruteIndex}][tujuan]" placeholder="Tujuan ke-${ruteIndex + 1}" required>
            <button type="button" class="btn btn-sm btn-danger remove-rute" onclick="removeRute(this)">
                <i class="fas fa-times"></i>
            </button>
        </div>
    `;
    container.appendChild(newItem);
    ruteIndex++;
    updateRuteNumbers();
}

function removeRute(button) {
    const item = button.closest('.rute-detail-item');
    if (document.querySelectorAll('.rute-detail-item').length <= 2) {
        alert('Minimal harus ada 2 rute!');
        return;
    }
    item.remove();
    updateRuteNumbers();
}

function updateRuteNumbers() {
    const items = document.querySelectorAll('.rute-detail-item');
    items.forEach((item, index) => {
        const number = item.querySelector('.rute-number');
        if (number) {
            number.textContent = `#${index + 1}`;
        }
        const input = item.querySelector('input');
        if (input) {
            input.name = `rute_details[${index}][tujuan]`;
            input.placeholder = `Tujuan ke-${index + 1}`;
        }
    });
}

// ============================================
// TAMBAH JADWAL
// ============================================
let jadwalIndex = 1;

function addJadwal() {
    const container = document.getElementById('jadwalContainer');
    const newItem = document.createElement('div');
    newItem.className = 'jadwal-item';
    newItem.innerHTML = `
        <select name="hari[]" required>
            <option value="">-- Hari --</option>
            <option value="Senin">Senin</option>
            <option value="Selasa">Selasa</option>
            <option value="Rabu">Rabu</option>
            <option value="Kamis">Kamis</option>
            <option value="Jumat">Jumat</option>
            <option value="Sabtu">Sabtu</option>
            <option value="Minggu">Minggu</option>
        </select>
        <input type="time" name="waktu_berangkat[]" required>
        <button type="button" class="btn btn-sm btn-danger remove-jadwal" onclick="removeJadwal(this)">
            <i class="fas fa-times"></i>
        </button>
    `;
    container.appendChild(newItem);
    jadwalIndex++;
}

function removeJadwal(button) {
    const item = button.closest('.jadwal-item');
    if (document.querySelectorAll('.jadwal-item').length <= 1) {
        alert('Minimal harus ada 1 jadwal!');
        return;
    }
    item.remove();
}
</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;
}

.form-card {
    background: #fff;
    padding: 1.5rem;
    border: 1px solid #e2e8f0;
    border-radius: 12px;
}

.form-group {
    margin-bottom: 1.2rem;
}

.form-group label {
    display: block;
    font-weight: 600;
    font-size: 0.9rem;
    color: #2d3748;
    margin-bottom: 0.3rem;
}

.form-group .required {
    color: #ef4444;
}

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

.form-group input, .form-group select {
    width: 100%;
    padding: 0.6rem 0.8rem;
    border: 1.5px solid #e2e8f0;
    border-radius: 6px;
    font-size: 0.9rem;
    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);
}

/* Rute Detail */
.rute-detail-item {
    margin-bottom: 0.5rem;
}

.rute-detail-input {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.rute-detail-input .rute-number {
    font-weight: 700;
    color: #2b6cb0;
    min-width: 30px;
}

.rute-detail-input input {
    flex: 1;
    padding: 0.5rem 0.7rem;
    border: 1.5px solid #e2e8f0;
    border-radius: 6px;
    font-size: 0.9rem;
    transition: all 0.3s ease;
}

.rute-detail-input input:focus {
    outline: none;
    border-color: #2b6cb0;
}

/* Jadwal */
.jadwal-item {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin-bottom: 0.5rem;
}

.jadwal-item select, .jadwal-item input {
    padding: 0.5rem 0.7rem;
    border: 1.5px solid #e2e8f0;
    border-radius: 6px;
    font-size: 0.9rem;
    transition: all 0.3s ease;
}

.jadwal-item select:focus, .jadwal-item input:focus {
    outline: none;
    border-color: #2b6cb0;
}

.jadwal-item select {
    flex: 1;
}

.jadwal-item input[type="time"] {
    width: 150px;
}

.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-sm { padding: 0.2rem 0.6rem; font-size: 0.7rem; }

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

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

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

@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-row { grid-template-columns: 1fr; }
    .rute-detail-input { flex-wrap: wrap; }
    .jadwal-item { flex-wrap: wrap; }
    .jadwal-item input[type="time"] { width: 100%; }
    .form-actions { flex-direction: column; }
    .form-actions .btn { width: 100%; justify-content: center; }
}
</style>

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