<?php
/**
 * reschedule.php - Halaman Ajukan Perubahan Jadwal Wisatawan
 * HANYA TANGGAL & ALASAN YANG BISA DIUBAH - DESTINASI DIHAPUS
 */
$activeMenu = 'riwayatPesanan';
$pageTitle = 'Ajukan Perubahan Jadwal - Wisatawan';
include __DIR__ . '/../layouts/header.php';

$pesanan = $pesanan ?? null;
$ruteList = $ruteList ?? [];
$user = $user ?? null;
$unreadCount = $unreadCount ?? 0;

if (!$pesanan) {
    header("Location: ?page=wisatawan&action=riwayat");
    exit;
}

// Cek apakah bisa reschedule
$canReschedule = false;
$errorMessage = '';

// Ambil status reschedule dari database jika ada kolom reschedule_status
// Jika tidak ada, bisa menggunakan logika sederhana
$rescheduleStatus = $pesanan['reschedule_status'] ?? null;

if ($pesanan['status_pesanan'] != 'confirmed' && $pesanan['status_pesanan'] != 'dikonfirmasi') {
    $errorMessage = '⚠️ Pesanan belum diverifikasi oleh supir kapal.';
} elseif ($pesanan['status_pembayaran'] != 'lunas') {
    $errorMessage = '⚠️ Pembayaran belum lunas. Silakan selesaikan pembayaran terlebih dahulu.';
} elseif ($pesanan['status_pesanan'] == 'completed' || $pesanan['status_pesanan'] == 'selesai') {
    $errorMessage = '⚠️ Pesanan sudah selesai. Tidak dapat mengubah jadwal.';
} elseif ($pesanan['status_pesanan'] == 'cancelled' || $pesanan['status_pesanan'] == 'dibatalkan') {
    $errorMessage = '⚠️ Pesanan sudah dibatalkan.';
} elseif ($rescheduleStatus == 'menunggu' || $rescheduleStatus == 'pending') {
    $errorMessage = '⏳ Pengajuan perubahan jadwal sedang diproses. Mohon tunggu.';
} elseif ($rescheduleStatus == 'disetujui' || $rescheduleStatus == 'approved') {
    $errorMessage = '✅ Perubahan jadwal sudah disetujui. Silakan cek jadwal baru.';
} else {
    $tanggalBerangkat = new DateTime($pesanan['tanggal_berangkat']);
    $now = new DateTime();
    $interval = $now->diff($tanggalBerangkat);
    $daysLeft = (int)$interval->format('%r%a'); // Bisa negatif jika sudah lewat
    
    if ($tanggalBerangkat < $now) {
        $errorMessage = '⚠️ Tanggal keberangkatan sudah lewat. Tidak dapat mengubah jadwal.';
    } elseif ($daysLeft < 1 && $daysLeft >= 0) {
        $errorMessage = '⚠️ Perubahan jadwal harus diajukan minimal 1 hari sebelum keberangkatan.';
    } else {
        $canReschedule = true;
    }
}
?>

<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_wisatawan.php'; ?>

    <main class="main-content">
        <div class="content-header">
            <div>
                <h2><i class="fas fa-calendar-alt" style="color:#f59e0b;"></i> Ajukan Perubahan Jadwal</h2>
                <p>Ubah jadwal keberangkatan pesanan Anda.</p>
            </div>
            <a href="?page=wisatawan&action=status&id=<?= $pesanan['id'] ?>" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Kembali
            </a>
        </div>

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

        <?php if(!$canReschedule): ?>
            <div class="info-box warning">
                <i class="fas fa-info-circle"></i>
                <div>
                    <strong>⚠️ Tidak Dapat Mengubah Jadwal</strong>
                    <p><?= $errorMessage ?></p>
                    <?php if($rescheduleStatus == 'menunggu' || $rescheduleStatus == 'pending'): ?>
                        <p class="mt-2">Status: <span class="badge badge-warning">Menunggu Konfirmasi</span></p>
                    <?php endif; ?>
                </div>
            </div>
            <div style="margin-top:1rem; text-align:center;">
                <a href="?page=wisatawan&action=status&id=<?= $pesanan['id'] ?>" class="btn btn-primary">
                    <i class="fas fa-arrow-left"></i> Kembali ke Detail Pesanan
                </a>
            </div>
        <?php else: ?>
            <!-- Form Reschedule -->
            <div class="reschedule-card">
                <div class="order-summary">
                    <h4>📋 Pesanan Saat Ini</h4>
                    <div class="summary-grid">
                        <div class="summary-item">
                            <span class="label">Kode Pesanan</span>
                            <span class="value"><?= htmlspecialchars($pesanan['kode_pesanan']) ?></span>
                        </div>
                        <div class="summary-item">
                            <span class="label">Kapal</span>
                            <span class="value"><?= htmlspecialchars($pesanan['nama_kapal']) ?></span>
                        </div>
                        <div class="summary-item">
                            <span class="label">Tanggal Berangkat</span>
                            <span class="value"><?= date('d/m/Y', strtotime($pesanan['tanggal_berangkat'])) ?></span>
                        </div>
                        <div class="summary-item">
                            <span class="label">Destinasi</span>
                            <span class="value"><?= htmlspecialchars($pesanan['pelabuhan_tujuan'] ?? '-') ?></span>
                        </div>
                    </div>
                </div>

                <form method="POST" action="?page=wisatawan&action=prosesReschedule" class="reschedule-form" id="rescheduleForm">
                    <input type="hidden" name="pesanan_id" value="<?= $pesanan['id'] ?>">

                    <!-- ============================================== -->
                    <!-- TANGGAL BARU -->
                    <!-- ============================================== -->
                    <div class="form-section">
                        <h4>📅 Pilih Tanggal Baru</h4>
                        <div class="form-group">
                            <label>Tanggal Keberangkatan Baru <span class="required">*</span></label>
                            <input type="date" name="tanggal_baru" class="form-input" 
                                   min="<?= date('Y-m-d', strtotime('+2 days')) ?>" 
                                   max="<?= date('Y-m-d', strtotime('+30 days')) ?>"
                                   value="<?= date('Y-m-d', strtotime($pesanan['tanggal_berangkat'] . ' +1 day')) ?>"
                                   required>
                            <small class="form-hint">Minimal H+2 dari hari ini, maksimal 30 hari ke depan.</small>
                        </div>
                    </div>

                    <!-- ============================================== -->
                    <!-- ALASAN PERUBAHAN -->
                    <!-- ============================================== -->
                    <div class="form-section">
                        <h4>📝 Alasan Perubahan</h4>
                        <div class="form-group">
                            <label>Alasan <span class="required">*</span></label>
                            <textarea name="alasan" class="form-control" rows="4" 
                                      placeholder="Jelaskan alasan Anda mengubah jadwal..."
                                      required></textarea>
                            <small class="form-hint">Minimal 10 karakter.</small>
                        </div>
                    </div>

                    <div class="info-box info">
                        <i class="fas fa-info-circle"></i>
                        <div>
                            <strong>ℹ️ Informasi</strong>
                            <p>Pengajuan perubahan jadwal akan dikirim ke supir kapal untuk persetujuan.</p>
                            <p>Jika disetujui, Anda akan mendapat notifikasi WhatsApp dan aplikasi.</p>
                            <p class="text-warning"><strong>⚠️ Destinasi wisata TIDAK DAPAT DIUBAH</strong> - hanya tanggal keberangkatan yang bisa diubah.</p>
                            <p class="text-warning">⚠️ Perubahan hanya bisa dilakukan 1x per pesanan.</p>
                        </div>
                    </div>

                    <div class="form-actions">
                        <a href="?page=wisatawan&action=status&id=<?= $pesanan['id'] ?>" class="btn btn-secondary">
                            <i class="fas fa-times"></i> Batal
                        </a>
                        <button type="submit" class="btn btn-warning" id="submitBtn">
                            <i class="fas fa-paper-plane"></i> Ajukan Perubahan
                        </button>
                    </div>
                </form>
            </div>
        <?php endif; ?>
    </main>
</div>

<!-- Tambahkan JavaScript untuk validasi -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('rescheduleForm');
    const submitBtn = document.getElementById('submitBtn');
    
    if (form) {
        form.addEventListener('submit', function(e) {
            const tanggalBaru = document.querySelector('input[name="tanggal_baru"]');
            const alasan = document.querySelector('textarea[name="alasan"]');
            let errors = [];
            
            // Validasi tanggal
            if (!tanggalBaru.value) {
                errors.push('Tanggal baru wajib dipilih');
            } else {
                const selectedDate = new Date(tanggalBaru.value);
                const today = new Date();
                today.setHours(0, 0, 0, 0);
                const minDate = new Date(today);
                minDate.setDate(minDate.getDate() + 2);
                
                if (selectedDate < minDate) {
                    errors.push('Tanggal baru minimal H+2 dari hari ini');
                }
            }
            
            // Validasi alasan
            if (!alasan.value.trim()) {
                errors.push('Alasan perubahan wajib diisi');
            } else if (alasan.value.trim().length < 10) {
                errors.push('Alasan minimal 10 karakter');
            }
            
            if (errors.length > 0) {
                e.preventDefault();
                alert('❌ ' + errors.join('\n'));
                return false;
            }
            
            // Konfirmasi sebelum submit
            if (!confirm('Yakin ingin mengajukan perubahan jadwal?\n\n' +
                         'Tanggal baru: ' + tanggalBaru.value + '\n' +
                         'Alasan: ' + alasan.value.trim().substring(0, 50) + '...')) {
                e.preventDefault();
                return false;
            }
            
            // Disable tombol untuk mencegah double submit
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Memproses...';
        });
    }
});
</script>

<style>
/* CSS sama seperti sebelumnya, tambahkan ini untuk spinner */
.btn-warning:disabled {
    opacity: 0.7;
    cursor: not-allowed;
}

.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: 1rem;
}

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

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

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

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

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

.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-warning {
    background: #f59e0b;
    color: #1a202c;
}

.btn-warning:hover {
    background: #d97706;
    color: #1a202c;
}

.badge {
    display: inline-flex;
    align-items: center;
    gap: 0.2rem;
    padding: 0.15rem 0.6rem;
    border-radius: 20px;
    font-size: 0.65rem;
    font-weight: 600;
}

.badge-warning {
    background: #fef3c7;
    color: #92400e;
}

.reschedule-card {
    display: grid;
    grid-template-columns: 1fr 1.5fr;
    gap: 1.5rem;
}

.order-summary {
    background: #f7fafc;
    border-radius: 12px;
    padding: 1.2rem;
    border: 1px solid #e2e8f0;
    height: fit-content;
}

.order-summary h4 {
    font-size: 0.95rem;
    font-weight: 700;
    color: #2d3748;
    margin-bottom: 0.8rem;
    padding-bottom: 0.3rem;
    border-bottom: 1px solid #e2e8f0;
}

.summary-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 0.5rem;
}

.summary-item {
    padding: 0.3rem 0;
}

.summary-item .label {
    display: block;
    font-size: 0.7rem;
    color: #718096;
    text-transform: uppercase;
    letter-spacing: 0.3px;
}

.summary-item .value {
    font-weight: 600;
    color: #1a202c;
    font-size: 0.9rem;
}

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

.reschedule-form .form-section {
    margin-bottom: 1.2rem;
}

.reschedule-form .form-section h4 {
    font-size: 0.9rem;
    font-weight: 700;
    color: #2d3748;
    margin-bottom: 0.5rem;
}

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

.form-group label {
    display: block;
    font-weight: 600;
    font-size: 0.85rem;
    color: #4a5568;
    margin-bottom: 0.2rem;
}

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

.form-input {
    width: 100%;
    padding: 0.6rem 0.8rem;
    border: 1.5px solid #e2e8f0;
    border-radius: 8px;
    font-size: 0.9rem;
    transition: all 0.3s ease;
}

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

.form-control {
    width: 100%;
    padding: 0.6rem 0.8rem;
    border: 1.5px solid #e2e8f0;
    border-radius: 8px;
    font-size: 0.9rem;
    transition: all 0.3s ease;
    font-family: inherit;
    resize: vertical;
}

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

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

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

.info-box {
    display: flex;
    gap: 0.8rem;
    padding: 0.8rem 1rem;
    border-radius: 8px;
    margin-top: 1rem;
}

.info-box.warning {
    background: #fef3c7;
    border: 1px solid #fcd34d;
}

.info-box.info {
    background: #dbeafe;
    border: 1px solid #93c5fd;
}

.info-box i {
    font-size: 1.5rem;
    color: #d97706;
}

.info-box.info i {
    color: #2563eb;
}

.info-box strong {
    color: #92400e;
    font-size: 0.85rem;
}

.info-box.info strong {
    color: #1e40af;
}

.info-box p {
    color: #92400e;
    font-size: 0.8rem;
    margin: 0.1rem 0;
}

.info-box.info p {
    color: #1e40af;
}

.text-warning {
    color: #92400e;
}

.mt-2 {
    margin-top: 0.5rem;
}

@media (max-width: 768px) {
    .dashboard-wrapper {
        flex-direction: column;
        padding: 0 12px;
        margin-top: 1rem;
    }
    .main-content {
        padding: 1rem;
    }
    .reschedule-card {
        grid-template-columns: 1fr;
    }
    .summary-grid {
        grid-template-columns: 1fr;
    }
    .content-header {
        flex-direction: column;
        align-items: flex-start;
    }
    .form-actions {
        flex-direction: column;
    }
    .form-actions .btn {
        width: 100%;
        justify-content: center;
    }
}

@media (max-width: 480px) {
    .main-content {
        padding: 0.8rem;
    }
}
</style>

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