<?php
session_start();
include '../functions.php';

if (empty($_SESSION['email'])) {
    header('Location: ../login');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_FILES['photo']['tmp_name'])) {
    header('Location: account-settings');
    exit;
}

$file     = $_FILES['photo'];
$ext      = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$allowed  = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

if (!in_array($ext, $allowed)) {
    header('Location: account-settings?error=invalid_type');
    exit;
}

if ($file['size'] > 2 * 1024 * 1024) {
    header('Location: account-settings?error=too_large');
    exit;
}

$filename = 'user_' . time() . '_' . mt_rand(1000, 9999) . '.' . $ext;
$dest     = '../uploads/profile_pictures/' . $filename;

if (!move_uploaded_file($file['tmp_name'], $dest)) {
    header('Location: account-settings?error=upload_failed');
    exit;
}

$email = $_SESSION['email'];
$stmt  = $conn->prepare("UPDATE users SET profile_img = ? WHERE email = ?");
$stmt->bind_param("ss", $filename, $email);
$stmt->execute();
$stmt->close();

header('Location: account-settings?success=1');
exit;
