<?php
/**
 * edit_profile.php - Halaman Edit Profil Supir
 * DIPERBAIKI - Menggunakan form submit biasa untuk upload foto
 */
include __DIR__ . '/../layouts/header.php';
$activeMenu = 'editProfile';

// ===== FALLBACK DATA =====
if (!isset($unreadCount)) $unreadCount = 0;
if (!isset($totalKapal)) $totalKapal = 0;
if (!isset($pesananMasuk)) $pesananMasuk = 0;

// Ambil data supir dari database
try {
    $stmt = $this->pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $supir = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$supir) {
        $supir = [];
        $supir['nama'] = $_SESSION['nama'] ?? 'Supir';
        $supir['email'] = $_SESSION['email'] ?? '';
        $supir['no_hp'] = $_SESSION['no_hp'] ?? '';
        $supir['foto'] = $_SESSION['foto'] ?? '';
        $supir['created_at'] = $_SESSION['created_at'] ?? date('Y-m-d H:i:s');
    }
} catch (Exception $e) {
    $supir = [];
    $supir['nama'] = $_SESSION['nama'] ?? 'Supir';
    $supir['email'] = $_SESSION['email'] ?? '';
    $supir['no_hp'] = $_SESSION['no_hp'] ?? '';
    $supir['foto'] = $_SESSION['foto'] ?? '';
    $supir['created_at'] = $_SESSION['created_at'] ?? date('Y-m-d H:i:s');
}

// Ambil total kapal
if (!isset($totalKapal)) {
    try {
        $stmt = $this->pdo->prepare("SELECT COUNT(*) as total FROM kapal WHERE pemilik_id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        $totalKapal = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
    } catch (Exception $e) {
        $totalKapal = 0;
    }
}

// ============================================
// CEK DAN VALIDASI FOTO PROFIL
// ============================================
$fotoUrl = '';
$hasFoto = false;

if (!empty($supir['foto'])) {
    $fotoFile = $supir['foto'];
    $physicalPath = __DIR__ . '/../../uploads/profile/' . $fotoFile;
    
    if (file_exists($physicalPath)) {
        $hasFoto = true;
        $fotoUrl = BASE_URL . '/uploads/profile/' . $fotoFile;
    } else {
        // Jika file tidak ada, hapus dari database
        try {
            $stmt = $this->pdo->prepare("UPDATE users SET foto = NULL WHERE id = ?");
            $stmt->execute([$_SESSION['user_id']]);
            $_SESSION['foto'] = '';
            $supir['foto'] = '';
        } catch (Exception $e) {
            // Ignore
        }
    }
}
?>

<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-user-edit" style="color:var(--primary);"></i> Edit Profil</h2>
                <p>Perbarui informasi profil Anda sebagai pemilik kapal.</p>
            </div>
            <div>
                <span class="date-badge">📅 <?= date('d F Y') ?></span>
            </div>
        </div>

        <!-- ALERT MESSAGES -->
        <?php if (isset($_SESSION['flash_success'])): ?>
            <div class="alert alert-success" id="successAlert">
                <i class="fas fa-check-circle"></i> <?= $_SESSION['flash_success'] ?>
                <?php unset($_SESSION['flash_success']); ?>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['flash_error'])): ?>
            <div class="alert alert-danger" id="errorAlert">
                <i class="fas fa-exclamation-circle"></i> <?= $_SESSION['flash_error'] ?>
                <?php unset($_SESSION['flash_error']); ?>
            </div>
        <?php endif; ?>

        <!-- PROFILE FORM -->
        <div class="profile-container">
            <!-- Left Column - Avatar & Info -->
            <div class="profile-card">
                <div class="avatar-section">
                    <!-- Avatar -->
                    <div class="avatar-container" id="avatarContainer">
                        <?php if ($hasFoto && !empty($fotoUrl)): ?>
                            <img src="<?= $fotoUrl ?>" alt="Profile Photo" id="profilePreview">
                        <?php else: ?>
                            <div class="avatar-text" id="avatarText"><?= strtoupper(substr($supir['nama'] ?? 'S', 0, 2)) ?></div>
                        <?php endif; ?>
                    </div>
                    
                    <!-- ========================================== -->
                    <!-- UPLOAD FOTO DENGAN FORM SUBMIT (BUKAN AJAX) -->
                    <!-- ========================================== -->
                    <form method="POST" action="?page=supir&action=updateProfilePhoto" enctype="multipart/form-data" id="uploadPhotoForm">
                        <div class="avatar-upload-btn">
                            <label class="btn-upload" style="cursor:pointer; display:inline-flex; align-items:center; gap:0.5rem; padding:0.4rem 1rem; background:var(--primary); color:#fff; border:none; border-radius:8px; font-size:0.8rem; font-weight:600; transition:var(--transition);">
                                <i class="fas fa-camera"></i> Ganti Foto
                                <input type="file" name="foto" accept="image/*" style="display:none;" onchange="document.getElementById('uploadPhotoForm').submit();">
                            </label>
                        </div>
                    </form>
                    
                    <div class="avatar-name"><?= htmlspecialchars($supir['nama'] ?? '') ?></div>
                    <div class="avatar-role"><i class="fas fa-user-tie"></i> Supir / Pemilik Kapal</div>
                    
                    <div style="margin-top:1.5rem; text-align:left;">
                        <div class="info-item"><i class="fas fa-envelope"></i> <span><?= htmlspecialchars($supir['email'] ?? '') ?></span></div>
                        <div class="info-item"><i class="fas fa-phone"></i> <span><?= htmlspecialchars($supir['no_hp'] ?? '-') ?></span></div>
                        <div class="info-item"><i class="fas fa-calendar-alt"></i> <span>Bergabung: <?= isset($supir['created_at']) ? date('d/m/Y', strtotime($supir['created_at'])) : '-' ?></span></div>
                        <div class="info-item"><i class="fas fa-ship"></i> <span>Total Kapal: <strong><?= $totalKapal ?? 0 ?></strong></span></div>
                    </div>
                </div>
            </div>

            <!-- Right Column - Form -->
            <div class="profile-card">
                <div class="card-title"><i class="fas fa-pen" style="color:var(--primary);"></i> Form Edit Profil</div>

                <form method="POST" action="?page=supir&action=updateProfile" id="profileForm">
                    <div class="form-group">
                        <label>Nama Lengkap <span class="required">*</span></label>
                        <input type="text" name="nama" value="<?= htmlspecialchars($supir['nama'] ?? '') ?>" required>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Email <span class="required">*</span></label>
                            <input type="email" name="email" value="<?= htmlspecialchars($supir['email'] ?? '') ?>" required>
                        </div>
                        <div class="form-group">
                            <label>Nomor HP <span class="required">*</span></label>
                            <input type="text" name="no_hp" value="<?= htmlspecialchars($supir['no_hp'] ?? '') ?>" required>
                        </div>
                    </div>

                    <div style="background:var(--gray-50); padding:1rem; border-radius:8px; margin:1.2rem 0;">
                        <p style="font-weight:600; color:var(--gray-700); font-size:0.85rem; margin-bottom:0.5rem;">
                            <i class="fas fa-lock" style="color:var(--warning);"></i> Ubah Password (Opsional)
                        </p>
                        <div class="form-row">
                            <div class="form-group" style="margin-bottom:0;">
                                <label>Password Baru</label>
                                <input type="password" name="password" placeholder="Kosongkan jika tidak diubah" id="newPassword">
                            </div>
                            <div class="form-group" style="margin-bottom:0;">
                                <label>Konfirmasi Password</label>
                                <input type="password" name="password_confirm" placeholder="Ulangi password baru" id="confirmPassword">
                            </div>
                        </div>
                        <p class="hint" style="margin-top:0.5rem;">
                            <i class="fas fa-info-circle"></i> Minimal 6 karakter. Kosongkan jika tidak ingin mengubah password.
                        </p>
                    </div>

                    <div class="form-actions">
                        <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Simpan Perubahan</button>
                        <a href="?page=supir&action=dashboard" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Kembali</a>
                    </div>
                </form>
            </div>
        </div>
    </main>
</div>

<style>
    /* ============================================
       ROOT VARIABLES - SAMA DENGAN DASHBOARD
       ============================================ */
    :root {
        --primary: #0f3b5e;
        --primary-light: #1a5276;
        --primary-dark: #0a2a42;
        --secondary: #e67e22;
        --success: #22c55e;
        --danger: #ef4444;
        --warning: #f59e0b;
        --info: #3b82f6;
        --gray-50: #f8fafc;
        --gray-100: #f1f5f9;
        --gray-200: #e2e8f0;
        --gray-300: #cbd5e1;
        --gray-400: #94a3b8;
        --gray-500: #64748b;
        --gray-600: #475569;
        --gray-700: #334155;
        --gray-800: #1e293b;
        --gray-900: #0f172a;
        --shadow: 0 4px 20px rgba(0,0,0,0.08);
        --shadow-lg: 0 10px 40px rgba(0,0,0,0.12);
        --radius: 12px;
        --transition: all 0.3s ease;
    }

    /* ============================================
       LAYOUT - SAMA DENGAN DASHBOARD
       ============================================ */
    .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 var(--gray-200);
    }

    /* ============================================
       HEADER - SAMA DENGAN DASHBOARD
       ============================================ */
    .content-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 1rem;
        margin-bottom: 1.5rem;
    }

    .content-header h2 {
        font-size: 1.5rem;
        font-weight: 700;
        color: var(--gray-900);
        display: flex;
        align-items: center;
        gap: 0.8rem;
        margin: 0;
    }

    .content-header h2 i { color: var(--primary); }

    .content-header p {
        color: var(--gray-500);
        font-size: 0.95rem;
        margin: 0;
    }

    .date-badge {
        background: var(--gray-100);
        padding: 0.3rem 1rem;
        border-radius: 20px;
        font-size: 0.8rem;
        color: var(--gray-600);
        white-space: nowrap;
    }

    /* ============================================
       ALERT - SAMA DENGAN DASHBOARD
       ============================================ */
    .alert {
        padding: 0.8rem 1.2rem;
        border-radius: 10px;
        margin-bottom: 1.5rem;
        display: flex;
        align-items: center;
        gap: 0.8rem;
        border-left: 4px solid transparent;
        animation: slideDown 0.3s ease;
    }

    .alert-success {
        background: #d1fae5;
        color: #065f46;
        border-left-color: var(--success);
    }

    .alert-danger {
        background: #fee2e2;
        color: #991b1b;
        border-left-color: var(--danger);
    }

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

    /* ============================================
       PROFILE CONTAINER
       ============================================ */
    .profile-container {
        display: grid;
        grid-template-columns: 1fr 2fr;
        gap: 2rem;
        max-width: 950px;
    }

    .profile-card {
        background: #fff;
        border-radius: 12px;
        padding: 1.5rem;
        border: 1px solid var(--gray-200);
        box-shadow: 0 2px 12px rgba(0,0,0,0.04);
        transition: var(--transition);
    }

    .profile-card:hover {
        box-shadow: 0 8px 30px rgba(0,0,0,0.06);
    }

    .profile-card .card-title {
        font-size: 1rem;
        font-weight: 700;
        color: var(--gray-800);
        margin-bottom: 1.2rem;
        padding-bottom: 0.8rem;
        border-bottom: 2px solid var(--gray-100);
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    /* ============================================
       AVATAR SECTION
       ============================================ */
    .avatar-section { text-align: center; }

    .avatar-section .avatar-container {
        position: relative;
        width: 150px;
        height: 150px;
        margin: 0 auto 1rem;
        border-radius: 50%;
        overflow: hidden;
        box-shadow: 0 8px 24px rgba(15,59,94,0.2);
        background: linear-gradient(135deg, var(--primary), var(--primary-light));
    }

    .avatar-section .avatar-container img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .avatar-section .avatar-container .avatar-text {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 4rem;
        font-weight: 700;
        color: #fff;
    }

    .avatar-section .avatar-upload-btn {
        display: inline-block;
    }

    .avatar-section .avatar-upload-btn .btn-upload {
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.4rem 1rem;
        background: var(--primary);
        color: #fff;
        border: none;
        border-radius: 8px;
        font-size: 0.8rem;
        font-weight: 600;
        cursor: pointer;
        transition: var(--transition);
    }

    .avatar-section .avatar-upload-btn .btn-upload:hover {
        background: var(--primary-dark);
        transform: translateY(-2px);
    }

    .avatar-section .avatar-name {
        font-size: 1.1rem;
        font-weight: 600;
        margin-top: 0.5rem;
    }

    .avatar-section .avatar-role {
        font-size: 0.8rem;
        color: var(--gray-500);
    }

    .avatar-section .info-item {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.5rem 0;
        border-bottom: 1px solid var(--gray-100);
        font-size: 0.85rem;
        color: var(--gray-600);
        text-align: left;
    }

    .avatar-section .info-item:last-child { border-bottom: none; }
    .avatar-section .info-item i { width: 20px; color: var(--primary); }

    /* ============================================
       FORM - SAMA DENGAN DASHBOARD
       ============================================ */
    .form-group { margin-bottom: 1.2rem; }

    .form-group label {
        display: block;
        font-weight: 600;
        font-size: 0.85rem;
        color: var(--gray-700);
        margin-bottom: 0.3rem;
    }

    .form-group label .required { color: var(--danger); margin-left: 0.2rem; }

    .form-group .hint {
        font-size: 0.75rem;
        color: var(--gray-400);
        margin-top: 0.2rem;
    }

    .form-group input,
    .form-group textarea {
        width: 100%;
        padding: 0.6rem 0.8rem;
        border: 1.5px solid var(--gray-200);
        border-radius: 8px;
        font-size: 0.9rem;
        transition: var(--transition);
        background: var(--gray-50);
        font-family: inherit;
    }

    .form-group input:focus,
    .form-group textarea:focus {
        outline: none;
        border-color: var(--primary);
        background: #fff;
        box-shadow: 0 0 0 3px rgba(15,59,94,0.08);
    }

    .form-group textarea { resize: vertical; min-height: 80px; }

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

    .form-actions {
        display: flex;
        gap: 0.8rem;
        margin-top: 1.5rem;
        padding-top: 1.2rem;
        border-top: 2px solid var(--gray-100);
    }

    /* ============================================
       BUTTONS - SAMA DENGAN DASHBOARD
       ============================================ */
    .btn {
        display: inline-flex;
        align-items: center;
        gap: 0.4rem;
        padding: 0.6rem 1.2rem;
        border: none;
        border-radius: 6px;
        font-weight: 600;
        font-size: 0.85rem;
        cursor: pointer;
        transition: var(--transition);
        text-decoration: none;
        font-family: inherit;
    }

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

    .btn-primary {
        background: var(--primary);
        color: #fff;
    }
    .btn-primary:hover {
        background: var(--primary-dark);
        color: #fff;
    }

    .btn-secondary {
        background: var(--gray-200);
        color: var(--gray-700);
    }
    .btn-secondary:hover {
        background: var(--gray-300);
        color: var(--gray-800);
    }

    /* ============================================
       RESPONSIVE - SAMA DENGAN DASHBOARD
       ============================================ */
    @media (max-width: 768px) {
        .dashboard-wrapper {
            flex-direction: column;
            padding: 0 12px;
            margin-top: 1rem;
        }
        .main-content {
            padding: 1rem;
        }
        .profile-container {
            grid-template-columns: 1fr;
            gap: 1rem;
        }
        .form-row {
            grid-template-columns: 1fr;
            gap: 0.5rem;
        }
        .form-actions {
            flex-direction: column;
        }
        .form-actions .btn {
            width: 100%;
            justify-content: center;
        }
        .content-header {
            flex-direction: column;
            align-items: flex-start;
        }
        .avatar-section .avatar-container {
            width: 120px;
            height: 120px;
        }
        .avatar-section .avatar-container .avatar-text {
            font-size: 3rem;
        }
    }

    @media (max-width: 480px) {
        .main-content {
            padding: 0.8rem;
        }
        .profile-card {
            padding: 1rem;
        }
        .avatar-section .avatar-container {
            width: 100px;
            height: 100px;
        }
        .avatar-section .avatar-container .avatar-text {
            font-size: 2.5rem;
        }
        .content-header h2 {
            font-size: 1.1rem;
        }
        .btn {
            font-size: 0.7rem;
            padding: 0.3rem 0.7rem;
        }
        .date-badge {
            font-size: 0.7rem;
            padding: 0.2rem 0.7rem;
        }
    }
</style>

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

    // ============================================
    // VALIDASI FORM SEBELUM SUBMIT
    // ============================================
    document.getElementById('profileForm').addEventListener('submit', function(e) {
        const password = document.getElementById('newPassword').value;
        const confirm = document.getElementById('confirmPassword').value;
        
        if (password && password.length < 6) {
            e.preventDefault();
            alert('Password minimal 6 karakter!');
            return false;
        }
        
        if (password !== confirm) {
            e.preventDefault();
            alert('Konfirmasi password tidak cocok!');
            return false;
        }
    });
</script>

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