<?php
session_start();
require_once '../config/database.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: ../admin_login.php');
    exit();
}

$id = $_GET['id'] ?? 0;
$active_page = 'kelola_kapal';
$success = '';
$error = '';

// Ambil data kapal
$kapal = $conn->prepare("SELECT * FROM kapal WHERE id = ?");
$kapal->bind_param("i", $id);
$kapal->execute();
$data = $kapal->get_result()->fetch_assoc();

if (!$data) {
    header('Location: kelola_kapal.php');
    exit();
}

// Proses update kapal
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
    $nama_kapal = trim($_POST['nama_kapal']);
    $jenis = $_POST['jenis'];
    $kapasitas = $_POST['kapasitas'];
    $harga_per_tiket = $_POST['harga_per_tiket'];
    $pelabuhan_asal = $_POST['pelabuhan_asal'];
    $pelabuhan_tujuan = $_POST['pelabuhan_tujuan'];
    $rute = $_POST['rute'];
    $jadwal_keberangkatan = $_POST['jadwal_keberangkatan'];
    $deskripsi = $_POST['deskripsi'];
    
    // Upload foto baru jika ada
    $foto = $data['foto'];
    if (isset($_FILES['foto']) && $_FILES['foto']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['foto'];
        $allowed = ['image/jpeg', 'image/png', 'image/jpg', 'image/webp'];
        $max_size = 2 * 1024 * 1024;
        
        if (!in_array($file['type'], $allowed)) {
            $error = "Format file tidak didukung. Gunakan JPG, PNG, atau WEBP.";
        } elseif ($file['size'] > $max_size) {
            $error = "Ukuran file terlalu besar. Maksimal 2MB.";
        } else {
            $upload_dir = '../uploads/kapal/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            // Hapus foto lama
            if ($foto && file_exists($upload_dir . $foto)) {
                unlink($upload_dir . $foto);
            }
            $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
            $foto = 'kapal_' . time() . '_' . uniqid() . '.' . $extension;
            move_uploaded_file($file['tmp_name'], $upload_dir . $foto);
        }
    }
    
    if (empty($error)) {
        $stmt = $conn->prepare("
            UPDATE kapal SET 
                nama_kapal = ?, 
                jenis = ?, 
                kapasitas = ?, 
                harga_per_tiket = ?,
                pelabuhan_asal = ?, 
                pelabuhan_tujuan = ?, 
                rute = ?, 
                jadwal_keberangkatan = ?, 
                deskripsi = ?, 
                foto = ?
            WHERE id = ?
        ");
        
        $stmt->bind_param("ssiissssssi", 
            $nama_kapal, $jenis, $kapasitas, $harga_per_tiket,
            $pelabuhan_asal, $pelabuhan_tujuan, $rute, $jadwal_keberangkatan,
            $deskripsi, $foto, $id
        );
        
        if ($stmt->execute()) {
            $success = "Kapal berhasil diupdate!";
            // Refresh data
            $kapal = $conn->prepare("SELECT * FROM kapal WHERE id = ?");
            $kapal->bind_param("i", $id);
            $kapal->execute();
            $data = $kapal->get_result()->fetch_assoc();
        } else {
            $error = "Gagal mengupdate kapal: " . $conn->error;
        }
        $stmt->close();
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Kapal - Admin Samosir Wisata</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Inter', sans-serif; background: #f0f2f5; }
        
        .sidebar {
            position: fixed; left: 0; top: 0; width: 280px; height: 100%;
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
            z-index: 1000;
        }
        .sidebar-header { padding: 30px 20px; text-align: center; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .sidebar-header i { font-size: 50px; }
        .sidebar-header h3 { font-size: 20px; margin-top: 10px; }
        .sidebar-header p { font-size: 12px; opacity: 0.8; margin-top: 5px; }
        .sidebar-menu { padding: 20px 0; }
        .menu-item {
            padding: 12px 25px; margin: 5px 15px; border-radius: 12px;
            display: flex; align-items: center; gap: 15px;
            color: rgba(255,255,255,0.8); text-decoration: none;
            transition: all 0.3s;
        }
        .menu-item:hover, .menu-item.active { background: rgba(255,255,255,0.2); color: white; transform: translateX(5px); }
        .menu-item i { width: 24px; }
        
        .main-content { margin-left: 280px; padding: 20px 30px; }
        
        .top-bar {
            background: white; border-radius: 15px; padding: 15px 25px;
            margin-bottom: 25px; display: flex; justify-content: space-between;
            align-items: center;
        }
        .page-title h2 { font-size: 24px; color: #333; }
        .user-info { display: flex; align-items: center; gap: 20px; }
        .user-avatar {
            width: 45px; height: 45px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 50%; display: flex; align-items: center;
            justify-content: center; color: white;
        }
        .logout-btn { background: #dc2626; color: white; padding: 8px 16px; border-radius: 10px; text-decoration: none; }
        
        .welcome-card {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            border-radius: 20px; padding: 25px; margin-bottom: 30px;
            color: white;
        }
        
        .form-card {
            background: white;
            border-radius: 20px;
            padding: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .form-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e0e0e0;
        }
        .form-header h3 { font-size: 18px; font-weight: 600; }
        
        .form-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
        }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; margin-bottom: 8px; font-weight: 600; }
        .form-group input, .form-group select, .form-group textarea {
            width: 100%; padding: 10px; border: 1px solid #ddd;
            border-radius: 8px;
        }
        
        .btn-submit {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white; padding: 12px; border: none; border-radius: 8px;
            cursor: pointer; width: 100%; margin-top: 20px;
        }
        .btn-back {
            background: #6c757d; color: white; padding: 8px 16px;
            border-radius: 8px; text-decoration: none;
        }
        
        .alert-success { background: #d1fae5; color: #059669; padding: 12px; border-radius: 8px; margin-bottom: 20px; }
        .alert-error { background: #fee2e2; color: #dc2626; padding: 12px; border-radius: 8px; margin-bottom: 20px; }
        .current-photo img { width: 100px; border-radius: 8px; }
        
        @media (max-width: 768px) {
            .sidebar { transform: translateX(-100%); }
            .main-content { margin-left: 0; }
            .form-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="sidebar-header">
            <i class="fas fa-user-shield"></i>
            <h3>Admin Panel</h3>
            <p>Samosir Wisata</p>
        </div>
        <div class="sidebar-menu">
            <a href="dashboard.php" class="menu-item"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
            <a href="kelola_kapal.php" class="menu-item active"><i class="fas fa-ship"></i> Kelola Kapal</a>
            <a href="verifikasi_kapal.php" class="menu-item"><i class="fas fa-check-circle"></i> Verifikasi Kapal</a>
            <a href="kelola_pesanan.php" class="menu-item"><i class="fas fa-ticket-alt"></i> Kelola Pesanan</a>
            <a href="jadwal.php" class="menu-item"><i class="fas fa-calendar-alt"></i> Jadwal Kapal</a>
            <a href="kelola_user.php" class="menu-item"><i class="fas fa-users"></i> Kelola User</a>
            <a href="laporan.php" class="menu-item"><i class="fas fa-chart-line"></i> Laporan</a>
        </div>
    </div>

    <div class="main-content">
        <div class="top-bar">
            <div class="page-title">
                <h2>Edit Kapal</h2>
            </div>
            <div class="user-info">
                <div class="user-avatar">A</div>
                <span>Admin</span>
                <a href="../logout.php" class="logout-btn">Logout</a>
            </div>
        </div>

        <div class="welcome-card">
            <h1>Edit Kapal: <?php echo htmlspecialchars($data['nama_kapal']); ?></h1>
        </div>

        <div class="form-card">
            <div class="form-header">
                <h3>Form Edit Kapal</h3>
                <a href="kelola_kapal.php" class="btn-back">Kembali</a>
            </div>

            <?php if ($success): ?>
                <div class="alert-success">✅ <?php echo $success; ?></div>
            <?php endif; ?>
            <?php if ($error): ?>
                <div class="alert-error">❌ <?php echo $error; ?></div>
            <?php endif; ?>

            <form method="POST" enctype="multipart/form-data">
                <div class="form-grid">
                    <div class="form-group">
                        <label>Nama Kapal *</label>
                        <input type="text" name="nama_kapal" value="<?php echo htmlspecialchars($data['nama_kapal']); ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Jenis Kapal *</label>
                        <select name="jenis" required>
                            <option value="speedboat" <?php echo $data['jenis'] == 'speedboat' ? 'selected' : ''; ?>>Speedboat</option>
                            <option value="kapal_kayu" <?php echo $data['jenis'] == 'kapal_kayu' ? 'selected' : ''; ?>>Kapal Kayu</option>
                            <option value="ferry" <?php echo $data['jenis'] == 'ferry' ? 'selected' : ''; ?>>Ferry</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Kapasitas (orang) *</label>
                        <input type="number" name="kapasitas" value="<?php echo $data['kapasitas']; ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Harga per Tiket *</label>
                        <input type="number" name="harga_per_tiket" value="<?php echo $data['harga_per_tiket']; ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Pelabuhan Asal</label>
                        <input type="text" name="pelabuhan_asal" value="<?php echo htmlspecialchars($data['pelabuhan_asal'] ?? 'Parapat'); ?>">
                    </div>
                    <div class="form-group">
                        <label>Pelabuhan Tujuan</label>
                        <input type="text" name="pelabuhan_tujuan" value="<?php echo htmlspecialchars($data['pelabuhan_tujuan'] ?? 'Tuk-Tuk'); ?>">
                    </div>
                    <div class="form-group">
                        <label>Rute</label>
                        <input type="text" name="rute" value="<?php echo htmlspecialchars($data['rute'] ?? 'Parapat - Tuk-Tuk'); ?>">
                    </div>
                    <div class="form-group">
                        <label>Jadwal Keberangkatan</label>
                        <input type="time" name="jadwal_keberangkatan" value="<?php echo $data['jadwal_keberangkatan'] ?? '08:00'; ?>">
                    </div>
                </div>

                <div class="form-group">
                    <label>Deskripsi</label>
                    <textarea name="deskripsi" rows="3"><?php echo htmlspecialchars($data['deskripsi'] ?? ''); ?></textarea>
                </div>
                
                <div class="form-group">
                    <label>Foto Kapal</label>
                    <?php if ($data['foto'] && file_exists('../uploads/kapal/' . $data['foto'])): ?>
                        <div class="current-photo">
                            <img src="../uploads/kapal/<?php echo $data['foto']; ?>">
                            <p><small>Foto saat ini</small></p>
                        </div>
                    <?php endif; ?>
                    <input type="file" name="foto" accept="image/*">
                    <small>Kosongkan jika tidak ingin mengubah foto</small>
                </div>

                <button type="submit" name="submit" class="btn-submit">
                    Update Kapal
                </button>
            </form>
        </div>
    </div>
</body>
</html>