<?php
require_once '../core/bootstrap.php';

// --- Authentication Check ---
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}
$user_id = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: profile.php');
    exit();
}

$userModel = new User();
$action = $_POST['action'] ?? '';

if ($action === 'update_details') {
    // --- Handle Profile Detail Update ---
    $data = [
        'id' => $user_id,
        'first_name' => trim($_POST['first_name'] ?? ''),
        'last_name' => trim($_POST['last_name'] ?? ''),
        'email' => trim($_POST['email'] ?? ''),
        'username' => trim($_POST['username'] ?? ''),
    ];

    // Basic validation
    if (empty($data['first_name']) || empty($data['last_name']) || empty($data['email']) || empty($data['username'])) {
        header('Location: profile.php?status=error&error=missing_fields');
        exit();
    }

    // Handle file upload for profile picture
    if (isset($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = '../uploads/profiles/';
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
        
        $file_ext = strtolower(pathinfo($_FILES['profile_picture']['name'], PATHINFO_EXTENSION));
        $allowed_ext = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

        if (in_array($file_ext, $allowed_ext)) {
            $user = $userModel->getFullUserDetailsById($user_id);
            if ($user && $user->profile_picture && file_exists($user->profile_picture)) {
                unlink($user->profile_picture); // Delete old picture
            }

            $filename = 'user_' . $user_id . '_' . uniqid() . '.' . $file_ext;
            $filepath = $upload_dir . $filename;

            if (move_uploaded_file($_FILES['profile_picture']['tmp_name'], $filepath)) {
                $data['profile_picture'] = $filepath;
            }
        }
    }

    if ($userModel->updateProfile($data)) {
        header('Location: profile.php?status=success');
    } else {
        header('Location: profile.php?status=error&error=db_error');
    }
    exit();

} elseif ($action === 'change_password') {
    // --- Handle Password Change ---
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
        header('Location: profile.php?status=error&error=missing_password_fields');
        exit();
    }

    if ($new_password !== $confirm_password) {
        header('Location: profile.php?status=error&error=password_mismatch');
        exit();
    }

    // Verify current password
    $user = $userModel->getFullUserDetailsById($user_id);
    if (!$user || !password_verify($current_password, $user->password_hash)) {
        header('Location: profile.php?status=error&error=incorrect_current_password');
        exit();
    }

    // Hash new password and update
    $new_password_hash = password_hash($new_password, PASSWORD_DEFAULT);
    if ($userModel->updatePassword($user_id, $new_password_hash)) {
        header('Location: profile.php?status=success');
    } else {
        header('Location: profile.php?status=error&error=db_error');
    }
    exit();

} else {
    // Invalid action
    header('Location: profile.php');
    exit();
}
?>