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

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

$userModel = new User();

// 1. Sanitize Inputs
$first_name = trim($_POST['first_name'] ?? '');
$last_name = trim($_POST['last_name'] ?? '');
$username = trim($_POST['username'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone_number = trim($_POST['phone_number'] ?? '');
$password = $_POST['password'] ?? '';
$confirm_password = $_POST['confirm_password'] ?? '';

// 2. Validate Inputs
if (empty($first_name) || empty($last_name) || empty($username) || empty($email) || empty($password)) {
    header('Location: register.php?error=' . urlencode('Please fill in all required fields.'));
    exit();
}

if ($password !== $confirm_password) {
    header('Location: register.php?error=' . urlencode('Passwords do not match.'));
    exit();
}

if ($userModel->findByEmail($email)) {
    header('Location: register.php?error=' . urlencode('Email is already registered.'));
    exit();
}

if ($userModel->findByUsername($username)) {
    header('Location: register.php?error=' . urlencode('Username is already taken.'));
    exit();
}

// 3. 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)) {
        // Generate unique filename
        $filename = 'user_' . uniqid() . '.' . $file_ext;
        $target = $upload_dir . $filename;
        
        if (move_uploaded_file($_FILES['profile_picture']['tmp_name'], $target)) {
            $profile_picture = '/smart_football/uploads/profiles/' . $filename;
        } else {
            // Optional: Handle upload failure specifically
        }
    }
}

// 4. Create User
$data = [
    'first_name' => $first_name,
    'last_name' => $last_name,
    'username' => $username,
    'email' => $email,
    'phone_number' => $phone_number,
    'password_hash' => password_hash($password, PASSWORD_DEFAULT),
    'profile_picture' => $profile_picture
];

if ($userModel->register($data)) {
    header('Location: login.php?registered=success');
} else {
    header('Location: register.php?error=' . urlencode('Registration failed. Please try again.'));
}
exit();