<?php
// Filename: profile.php
require 'config.php';
requireLogin();

/**
 * Helper to convert uploaded images to WebP immediately
 * Helps reduce LCP latency and server storage
 */
function convertToWebP($source, $destination, $quality = 80) {
    $info = getimagesize($source);
    if ($info['mime'] == 'image/jpeg') {
        $image = imagecreatefromjpeg($source);
    } elseif ($info['mime'] == 'image/png') {
        $image = imagecreatefrompng($source);
        imagepalettetotruecolor($image);
        imagealphablending($image, true);
        imagesavealpha($image, true);
    } else {
        return false;
    }
    $result = imagewebp($image, $destination, $quality);
    imagedestroy($image);
    return $result;
}

// --- SECURITY: CSRF TOKEN ---
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$user_id = $_SESSION['user_id'];
$role = $_SESSION['role']; 
$is_akp = (strpos($role, 'akp') !== false);

$msg = '';
$msg_type = '';
$mode = $_GET['mode'] ?? ''; 

$all_subjects = $pdo->query("SELECT subject_name FROM subjects ORDER BY subject_name ASC")->fetchAll(PDO::FETCH_COLUMN);

// --- FORM HANDLING ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        die("Security Alert: Invalid Request (CSRF).");
    }

    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone_number'] ?? '');
    $tg_id = trim($_POST['telegram_chat_id'] ?? '');
    $new_pass = $_POST['new_password'] ?? '';
    $avatar_path = $_SESSION['avatar'] ?? null;
    
    $rem_enabled = isset($_POST['reminder_enabled']) ? 1 : 0;
    $rem_mins = intval($_POST['reminder_minutes'] ?? 15);
    $rem_sound = $_POST['reminder_sound'] ?? 'beep';
    $layout_mode = $_POST['layout_mode'] ?? 'right';
    $time_fmt = $_POST['time_format'] ?? '12'; 
    $my_subjects = isset($_POST['subjects']) ? implode(',', $_POST['subjects']) : '';

    try {
        // --- IMPROVED UPLOAD & CONVERSION LOGIC ---
        if (isset($_FILES['avatar_file']) && $_FILES['avatar_file']['error'] == 0) {
            $target_dir = "uploads/avatars/";
            if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);
            
            $temp_path = $_FILES["avatar_file"]["tmp_name"];
            $ext = strtolower(pathinfo($_FILES["avatar_file"]["name"], PATHINFO_EXTENSION));
            
            if (in_array($ext, ['jpg', 'jpeg', 'png'])) {
                $new_filename = "user_" . $user_id . "_" . time() . ".webp";
                $target_file = $target_dir . $new_filename;
                
                if (convertToWebP($temp_path, $target_file)) {
                    // Cleanup old file if it exists to save space
                    if (!empty($avatar_path) && file_exists($avatar_path)) {
                        @unlink($avatar_path);
                    }
                    $avatar_path = $target_file;
                    $_SESSION['avatar'] = $avatar_path;
                }
            }
        }

        $sql = "UPDATE users SET email=?, phone_number=?, telegram_chat_id=?, avatar=?, reminder_enabled=?, reminder_minutes=?, reminder_sound=?, layout_mode=?, subjects=?, time_format=?";
        $params = [$email, $phone, $tg_id, $avatar_path, $rem_enabled, $rem_mins, $rem_sound, $layout_mode, $my_subjects, $time_fmt];

        if (!empty($new_pass)) {
            $sql .= ", password=?";
            $params[] = password_hash($new_pass, PASSWORD_BCRYPT);
        }

        $sql .= " WHERE id=?";
        $params[] = $user_id;

        $pdo->prepare($sql)->execute($params);
        $_SESSION['layout_mode'] = $layout_mode;

        if ($mode === 'onboarding') { header("Location: dashboard.php"); exit; }
        $msg = "Profile updated successfully.";
        $msg_type = "success";

    } catch (Exception $e) {
        $msg = "Error: " . $e->getMessage();
        $msg_type = "danger";
    }
}

// Fetch User Data
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

if (!$user) {
    session_destroy();
    header("Location: index.php"); 
    exit;
}

$user_subjects = array_map('trim', explode(',', $user['subjects'] ?? ''));
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>My Profile</title>
    
    <link rel="preload" href="/assets/fonts/PlusJakartaSans-Regular.woff2" as="font" type="font/woff2" crossorigin>
    <link rel="preload" href="/assets/fonts/PlusJakartaSans-SemiBold.woff2" as="font" type="font/woff2" crossorigin>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" media="print" onload="this.media='all'">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">

    <style>
        /* FONT-FACE DEFINITIONS */
        @font-face {
            font-family: 'Plus Jakarta Sans';
            src: url('/assets/fonts/PlusJakartaSans-Regular.woff2') format('woff2');
            font-weight: 400; font-style: normal; font-display: swap;
        }
        @font-face {
            font-family: 'Plus Jakarta Sans';
            src: url('/assets/fonts/PlusJakartaSans-SemiBold.woff2') format('woff2');
            font-weight: 600; font-style: normal; font-display: swap;
        }

        :root { --primary-grad: <?= getHeaderTheme() ?>; --bg-color: #f8f9fd; --text-dark: #1e293b; --text-gray: #64748b; }
        body { font-family: 'Plus Jakarta Sans', system-ui, -apple-system, sans-serif; background-color: var(--bg-color); padding-bottom: 90px; }

        .app-header { background: var(--primary-grad); padding: 30px 20px 70px 20px; border-radius: 0 0 35px 35px; color: white; text-align: center; }
        .avatar-container { position: relative; width: 100px; height: 100px; margin: 0 auto 15px auto; }
        .avatar-img { width: 100%; height: 100%; object-fit: cover; border-radius: 50%; border: 4px solid rgba(255,255,255,0.3); background: #fff; }
        .camera-badge { position: absolute; bottom: 0; right: 0; background: #1e293b; color: white; width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; border: 2px solid white; cursor: pointer; }

        .floating-card { background: white; margin: -60px 20px 0 20px; border-radius: 24px; padding: 10px; box-shadow: 0 15px 35px rgba(0,0,0,0.08); position: relative; z-index: 20; }
        .accordion-item { border: none; border-bottom: 1px solid #f1f5f9; }
        .accordion-button { font-weight: 600; color: var(--text-dark); padding: 1.25rem 1rem; border-radius: 16px !important; }
        .accordion-button:not(.collapsed) { background-color: #f8f7ff; color: #8B5CF6; box-shadow: none; }
        .form-label { font-size: 0.75rem; font-weight: 700; color: var(--text-gray); text-transform: uppercase; letter-spacing: 0.5px; }
        .form-control, .form-select { border-radius: 12px; padding: 12px; border: 1px solid #e2e8f0; background-color: #f8fafc; }
        .btn-theme { background: var(--primary-grad); border: none; color: white; transition: transform 0.2s; }
        .subj-check { display: none; }
        .subj-label { display: inline-block; padding: 8px 14px; margin: 3px; border-radius: 12px; border: 1px solid #e2e8f0; background: #f8fafc; color: var(--text-gray); font-size: 0.85rem; cursor: pointer; transition: 0.2s; }
        .subj-check:checked + .subj-label { background-color: #8B5CF6; color: white; border-color: #8B5CF6; }
    </style>
</head>
<body>

    <form method="POST" enctype="multipart/form-data" id="profileForm">
    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
    <input type="hidden" name="layout_mode" value="<?= htmlspecialchars($user['layout_mode'] ?? 'right') ?>">

    <div class="app-header">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <a href="<?= $is_akp ? 'akp_dashboard.php' : 'dashboard.php' ?>" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
            <div class="fw-bold">My Profile</div>
            <button type="submit" class="btn btn-sm btn-light rounded-pill px-3 fw-bold text-primary">Save</button>
        </div>

        <div class="avatar-container">
            <?php if(!empty($user['avatar']) && file_exists($user['avatar'])): ?>
                <img src="<?= $user['avatar'] ?>" class="avatar-img" id="previewImg">
            <?php else: ?>
                <div class="avatar-img d-flex align-items-center justify-content-center text-secondary fs-1 bg-white"><i class="bi bi-person"></i></div>
                <img src="" class="avatar-img d-none" id="previewImg">
            <?php endif; ?>
            <label class="camera-badge shadow-sm">
                <i class="bi bi-camera-fill small"></i>
                <input type="file" name="avatar_file" id="fileInput" class="d-none" accept="image/*">
            </label>
        </div>
        <h5 class="mb-0 fw-bold"><?= htmlspecialchars($user['full_name']) ?></h5>
        <small class="opacity-75">@<?= htmlspecialchars($user['username']) ?></small>
    </div>

    <div class="px-4 mt-n2">
        <?php if($msg): ?>
            <div class="alert alert-<?= $msg_type ?> border-0 shadow-sm rounded-4 mb-3 text-center small"><?= $msg ?></div>
        <?php endif; ?>
    </div>

    <div class="floating-card">
        <div class="accordion" id="profileAccordion">
            
            <div class="accordion-item">
                <h2 class="accordion-header">
                    <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne">
                        <i class="bi bi-person-lines-fill me-3 fs-5"></i> Personal Info
                    </button>
                </h2>
                <div id="collapseOne" class="accordion-collapse collapse show" data-bs-parent="#profileAccordion">
                    <div class="accordion-body">
                        <div class="mb-3">
                            <label class="form-label">Email</label>
                            <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($user['email'] ?? '') ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Phone</label>
                            <input type="tel" name="phone_number" class="form-control" value="<?= htmlspecialchars($user['phone_number']) ?>">
                        </div>
                        <div>
                            <label class="form-label text-primary"><i class="bi bi-telegram me-1"></i>Telegram Chat ID</label>
                            <div class="input-group">
                                <input type="text" name="telegram_chat_id" class="form-control" value="<?= htmlspecialchars($user['telegram_chat_id'] ?? '') ?>" placeholder="Numeric ID">
                                <a href="https://t.me/userinfobot" target="_blank" class="btn btn-light border"><i class="bi bi-arrow-up-right"></i></a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="accordion-item">
                <h2 class="accordion-header">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo">
                        <i class="bi bi-shield-lock-fill me-3 fs-5"></i> Security
                    </button>
                </h2>
                <div id="collapseTwo" class="accordion-collapse collapse" data-bs-parent="#profileAccordion">
                    <div class="accordion-body">
                        <label class="form-label">New Password</label>
                        <input type="password" name="new_password" class="form-control" placeholder="Leave blank to keep current">
                    </div>
                </div>
            </div>

            <?php if (!$is_akp): ?>
            <div class="accordion-item">
                <h2 class="accordion-header">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree">
                        <i class="bi bi-sliders me-3 fs-5"></i> App Settings
                    </button>
                </h2>
                <div id="collapseThree" class="accordion-collapse collapse" data-bs-parent="#profileAccordion">
                    <div class="accordion-body">
                        <div class="form-check form-switch mb-3 p-0 d-flex justify-content-between align-items-center">
                            <label class="form-check-label fw-bold ms-1" for="remCheck">Popup Alerts</label>
                            <input class="form-check-input ms-0 float-none" type="checkbox" name="reminder_enabled" value="1" id="remCheck" <?= ($user['reminder_enabled']??1) ? 'checked' : '' ?> style="width: 3em; height: 1.5em;">
                        </div>
                        <div class="row g-2 mb-3">
                            <div class="col-6">
                                <label class="form-label">Alert Before (min)</label>
                                <input type="number" name="reminder_minutes" class="form-control text-center" value="<?= $user['reminder_minutes'] ?? 15 ?>">
                            </div>
                            <div class="col-6">
                                <label class="form-label">Sound</label>
                                <select name="reminder_sound" class="form-select">
                                    <option value="beep" <?= ($user['reminder_sound']=='beep')?'selected':'' ?>>Beep</option>
                                    <option value="chime" <?= ($user['reminder_sound']=='chime')?'selected':'' ?>>Chime</option>
                                    <option value="alarm" <?= ($user['reminder_sound']=='alarm')?'selected':'' ?>>Alarm</option>
                                </select>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Time Format</label>
                            <div class="btn-group w-100" role="group">
                                <input type="radio" class="btn-check" name="time_format" id="fmt12" value="12" <?= ($user['time_format'] ?? '12') == '12' ? 'checked' : '' ?>>
                                <label class="btn btn-outline-light text-dark border" for="fmt12">12H (2 PM)</label>
                                <input type="radio" class="btn-check" name="time_format" id="fmt24" value="24" <?= ($user['time_format'] ?? '12') == '24' ? 'checked' : '' ?>>
                                <label class="btn btn-outline-light text-dark border" for="fmt24">24H (14:00)</label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <?php if($role !== 'student' && !$is_akp): ?>
            <div class="accordion-item">
                <h2 class="accordion-header">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseFour">
                        <i class="bi bi-book-half me-3 fs-5"></i> My Subjects
                    </button>
                </h2>
                <div id="collapseFour" class="accordion-collapse collapse" data-bs-parent="#profileAccordion">
                    <div class="accordion-body">
                        <div class="d-flex flex-wrap gap-1">
                            <?php foreach($all_subjects as $subj): ?>
                                <input type="checkbox" name="subjects[]" value="<?= $subj ?>" id="subj_<?= md5($subj) ?>" class="subj-check" <?= in_array($subj, $user_subjects) ? 'checked' : '' ?>>
                                <label for="subj_<?= md5($subj) ?>" class="subj-label"><?= htmlspecialchars($subj) ?></label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php endif; ?>

        </div>
        
        <div class="mt-4 text-center">
            <button type="submit" class="btn btn-theme px-5 py-2 rounded-pill fw-bold shadow-sm" style="min-width: 200px;">Save Changes</button>
        </div>
    </div>
    </form>

    <?php include 'menu.php'; ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.getElementById('fileInput').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const img = document.getElementById('previewImg');
                    const ph = document.querySelector('.avatar-img.text-secondary'); 
                    img.src = e.target.result; img.classList.remove('d-none');
                    if(ph) ph.classList.add('d-none');
                }
                reader.readAsDataURL(file);
            }
        });
    </script>
</body>
</html>