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

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

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

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

if ($action === 'update_profile') {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    
    // Handle File Upload
    $profile_picture = null;
    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 = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        
        if (in_array($file_ext, $allowed)) {
            $filename = 'user_' . $user_id . '_' . time() . '.' . $file_ext;
            $target = $upload_dir . $filename;
            if (move_uploaded_file($_FILES['profile_picture']['tmp_name'], $target)) {
                $profile_picture = '/smart_football/uploads/profiles/' . $filename;
            }
        }
    }

    // Get current data to preserve profile pic if not updated
    $currentUser = $userModel->getFullUserDetailsById($user_id);
    if (!$profile_picture) {
        $profile_picture = $currentUser->profile_picture;
    }

    $data = [
        'id' => $user_id,
        'first_name' => $first_name,
        'last_name' => $last_name,
        'username' => $username,
        'email' => $email,
        'profile_picture' => $profile_picture
    ];

    if ($userModel->updateProfile($data)) {
        // Update session data
        $_SESSION['user_name'] = $first_name . ' ' . $last_name;
        $_SESSION['user_email'] = $email;
        header('Location: settings.php?status=success');
    } else {
        header('Location: settings.php?status=error&msg=Failed to update profile');
    }

} elseif ($action === 'change_password') {
    $current_password = $_POST['current_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];

    if ($new_password !== $confirm_password) {
        header('Location: settings.php?status=error&msg=New passwords do not match');
        exit();
    }

    $user = $userModel->getFullUserDetailsById($user_id);
    if ($user && password_verify($current_password, $user->password_hash)) {
        $new_hash = password_hash($new_password, PASSWORD_DEFAULT);
        if ($userModel->updatePassword($user_id, $new_hash)) {
            header('Location: settings.php?status=password_updated');
        } else {
            header('Location: settings.php?status=error&msg=Failed to update password');
        }
    } else {
        header('Location: settings.php?status=error&msg=Incorrect current password');
    }
} else {
    header('Location: settings.php');
}
exit();