<?php
// --- LOGIC BLOCK: All PHP processing must happen before any HTML is sent ---
include 'header.php'; // Includes user session, DB connection, and current user data in the '$user' variable
require_once '../includes/image-resizer.php'; 

$message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // --- Update Profile Details ---
    if (isset($_POST['update_details'])) {
        $title = trim($_POST['title']);
        $full_name = trim(strip_tags($_POST['full_name']));
        $suffix = trim(strip_tags($_POST['suffix']));
        $phone_number = trim(strip_tags($_POST['phone_number']));

        $stmt = $conn->prepare("UPDATE users SET title = ?, full_name = ?, suffix = ?, phone_number = ? WHERE id = ?");
        $stmt->bind_param("ssssi", $title, $full_name, $suffix, $phone_number, $user_id);
        
        if ($stmt->execute()) {
            $_SESSION['user_name'] = $full_name; // Update session name immediately
            $message .= '<div class="alert alert-success">Profile details updated successfully.</div>';
        } else {
            $message .= '<div class="alert alert-danger">Error updating details. Please try again.</div>';
        }
    }

    // --- Change Password ---
    if (isset($_POST['change_password'])) {
        $current_password = $_POST['current_password'];
        $new_password = $_POST['new_password'];
        $confirm_password = $_POST['confirm_password'];

        // Verify the user's current password before allowing a change
        if (password_verify($current_password, $user['password'])) {
            if (strlen($new_password) < 8) {
                $message .= '<div class="alert alert-danger">New password must be at least 8 characters long.</div>';
            } elseif ($new_password !== $confirm_password) {
                $message .= '<div class="alert alert-danger">New passwords do not match.</div>';
            } else {
                $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                $stmt_pass = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
                $stmt_pass->bind_param("si", $hashed_password, $user_id);
                $stmt_pass->execute();
                $message .= '<div class="alert alert-success">Password changed successfully.</div>';
            }
        } else {
            $message .= '<div class="alert alert-danger">Your Current Password was incorrect.</div>';
        }
    }

    // --- Handle Profile Picture Upload ---
    if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] == 0) {
        $target_dir = "../uploads/profiles/";
        if (!is_dir($target_dir)) { @mkdir($target_dir, 0755, true); }
        $image_extension = strtolower(pathinfo($_FILES["profile_image"]["name"], PATHINFO_EXTENSION));
        $target_file = $target_dir . "profile-" . $user_id . "." . $image_extension;
        
        // Resize to a 400x400 square, perfect for profile pictures
        if (resizeImage($_FILES["profile_image"]["tmp_name"], $target_file, 400, 400)) {
            $new_image_url = str_replace('../', '', $target_file) . '?v=' . time(); // Add version to break browser cache
            $stmt_img = $conn->prepare("UPDATE users SET profile_image_url = ? WHERE id = ?");
            $stmt_img->bind_param("si", $new_image_url, $user_id);
            $stmt_img->execute();
            $message .= '<div class="alert alert-success">Profile picture updated successfully.</div>';
        } else {
            $message .= '<div class="alert alert-danger">Failed to upload or resize image. Please use a valid JPG or PNG file.</div>';
        }
    }
    
    // After any potential update, re-fetch the user data to display the latest version on the page
    $stmt_refresh = $conn->prepare("SELECT * FROM users WHERE id = ?");
    $stmt_refresh->bind_param("i", $user_id);
    $stmt_refresh->execute();
    $user = $stmt_refresh->get_result()->fetch_assoc();
}

// --- PRESENTATION BLOCK ---
?>
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">Edit Profile</h1>
</div>

<?php echo $message; ?>

<div class="row">
    <div class="col-lg-8">
        <form method="POST" enctype="multipart/form-data">
            <div class="card shadow-sm mb-4">
                <div class="card-header">My Details</div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Title</label>
                            <select name="title" class="form-select">
                                <option value="Mr." <?php if($user['title'] == 'Mr.') echo 'selected'; ?>>Mr.</option>
                                <option value="Ms." <?php if($user['title'] == 'Ms.') echo 'selected'; ?>>Ms.</option>
                                <option value="Mrs." <?php if($user['title'] == 'Mrs.') echo 'selected'; ?>>Mrs.</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Full Name</label>
                            <input type="text" name="full_name" class="form-control" value="<?php echo htmlspecialchars($user['full_name']); ?>" required>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Suffix</label>
                            <input type="text" name="suffix" class="form-control" value="<?php echo htmlspecialchars($user['suffix'] ?? ''); ?>" placeholder="e.g., Jr., III">
                        </div>
                    </div>
                    <div class="mb-3"><label class="form-label">Email Address</label><input type="email" class="form-control" value="<?php echo htmlspecialchars($user['email']); ?>" disabled><small class="text-muted">Email cannot be changed.</small></div>
                    <div class="mb-3"><label class="form-label">Contact Phone</label><input type="text" name="phone_number" class="form-control" value="<?php echo htmlspecialchars($user['phone_number'] ?? ''); ?>"></div>
                    <button type="submit" name="update_details" class="btn btn-primary">Save Details</button>
                </div>
            </div>

            <div class="card shadow-sm mb-4">
                <div class="card-header">Profile Picture</div>
                <div class="card-body">
                     <div class="mb-3">
                        <label class="form-label">Upload New Picture</label>
                        <input type="file" name="profile_image" class="form-control" accept="image/jpeg, image/png">
                        <?php if (!empty($user['profile_image_url'])): ?>
                            <div class="mt-2"><small>Current Picture:</small><br><img src="../<?php echo htmlspecialchars($user['profile_image_url']); ?>" class="img-thumbnail rounded-circle" style="width: 150px; height: 150px; object-fit: cover;"></div>
                        <?php endif; ?>
                     </div>
                     <button type="submit" class="btn btn-secondary">Upload Picture</button>
                </div>
            </div>

            <div class="card shadow-sm mb-4">
                <div class="card-header">Change Password</div>
                <div class="card-body">
                    <form method="POST">
                        <div class="mb-3"><label class="form-label">Current Password</label><input type="password" name="current_password" class="form-control" required></div>
                        <div class="mb-3"><label class="form-label">New Password (min. 8 characters)</label><input type="password" name="new_password" class="form-control" required></div>
                        <div class="mb-3"><label class="form-label">Confirm New Password</label><input type="password" name="confirm_password" class="form-control" required></div>
                        <button type="submit" name="change_password" class="btn btn-primary">Change Password</button>
                    </form>
                </div>
            </div>
        </form>
    </div>
</div>

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