<?php
// 1. INCLUDE THE UNIFIED HEADER
// This handles security, DB connection, user data, and the top navbar.
require_once 'dashboard-logic.php';
include '../includes/header.php';

// --- Page-Specific Logic Starts Here ---
// The $user_id and $user_data variables are available from the header.

// 2. HANDLE PROFILE UPDATE FORM SUBMISSION
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_profile') {
    $full_name = trim($_POST['full_name']);
    $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

    // Handle profile picture upload
    if (isset($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = '../uploads/avatars/';
        if (!is_dir($upload_dir)) { mkdir($upload_dir, 0755, true); }
        
        $file_info = pathinfo($_FILES['profile_picture']['name']);
        $extension = strtolower($file_info['extension']);
        $unique_filename = "user" . $user_id . "-" . time() . "." . $extension;
        $target_path = $upload_dir . $unique_filename;
        
        // Ensure the helpers file is included to use the resize function
        require_once '../includes/helpers.php';

        if (move_uploaded_file($_FILES['profile_picture']['tmp_name'], $target_path)) {
            if (function_exists('resize_and_save_image')) {
                resize_and_save_image($target_path, $target_path, 200, 200);
            }
            
            $db_path = 'uploads/avatars/' . $unique_filename;
            $stmt_img = $conn->prepare("UPDATE users SET profile_image_url = ? WHERE id = ?");
            $stmt_img->bind_param("si", $db_path, $user_id);
            $stmt_img->execute();
            $stmt_img->close();
        }
    }
    
    // Update name and email
    if (!empty($full_name) && $email) {
        $stmt = $conn->prepare("UPDATE users SET full_name = ?, email = ? WHERE id = ?");
        $stmt->bind_param("ssi", $full_name, $email, $user_id);
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "Profile updated successfully!";
        } else {
            $_SESSION['error_message'] = "Error updating profile. The email may already be in use.";
        }
        $stmt->close();
    } else {
        $_SESSION['error_message'] = "Full Name and a valid Email are required.";
    }
    
    header("Location: profile.php");
    exit();
}

// 3. FETCH LATEST USER DATA for displaying on the page
// We re-fetch here to ensure the most current data is shown after potential updates
$stmt_profile = $conn->prepare("SELECT full_name, email, created_at, profile_image_url FROM users WHERE id = ?");
$stmt_profile->bind_param("i", $user_id);
$stmt_profile->execute();
$profile_user = $stmt_profile->get_result()->fetch_assoc();
$stmt_profile->close();
?>

<div class="container my-5">
    <div class="dashboard-content">
        <h1 class="h2 mb-4">Profile Settings</h1>

        <?php if (isset($_SESSION['success_message'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert"><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
        <?php endif; ?>
        <?php if (isset($_SESSION['error_message'])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
        <?php endif; ?>

        <div class="card shadow-sm">
            <div class="card-header bg-light">
                <h5 class="mb-0"><i class="bi bi-person-lines-fill me-2"></i>Personal Information</h5>
            </div>
            <div class="card-body p-4">
                <form action="profile.php" method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="update_profile">
                    <div class="row">
                        <div class="col-lg-8">
                            <div class="mb-3 row">
                                <label for="full_name" class="col-sm-3 col-form-label">Full Name</label>
                                <div class="col-sm-9"><input type="text" class="form-control" id="full_name" name="full_name" value="<?php echo htmlspecialchars($profile_user['full_name']); ?>" required></div>
                            </div>
                            <div class="mb-3 row">
                                <label for="email" class="col-sm-3 col-form-label">Email Address</label>
                                <div class="col-sm-9"><input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($profile_user['email']); ?>" required></div>
                            </div>
                            <div class="mb-3 row">
                                <label class="col-sm-3 col-form-label">Member Since</label>
                                <div class="col-sm-9"><p class="form-control-plaintext"><?php echo date('F j, Y', strtotime($profile_user['created_at'])); ?></p></div>
                            </div>
                        </div>
                        <div class="col-lg-4 text-center">
                            <label for="profile_picture" class="form-label">Profile Picture</label>
                            <?php $avatar_src = !empty($profile_user['profile_image_url']) ? '/' . htmlspecialchars($profile_user['profile_image_url']) : 'https://via.placeholder.com/200?text=No+Image'; ?>
                            <img src="<?php echo $avatar_src; ?>" class="img-fluid rounded-circle mb-2 border" alt="Avatar Preview" style="width: 200px; height: 200px; object-fit: cover;">
                            <input type="file" class="form-control" id="profile_picture" name="profile_picture" accept="image/png, image/jpeg, image/gif">
                        </div>
                    </div>
                    <div class="d-flex justify-content-end mt-4 border-top pt-3">
                        <button type="submit" class="btn btn-primary">Save Changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include '../includes/footer.php'; ?>
