<?php
if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.gc_maxlifetime', 31536000);
    ini_set('session.cookie_lifetime', 31536000);
    session_start();
}

require_once 'db.php';

if (!isset($_SESSION['logged_in_user'])) {
    http_response_code(403);
    exit("Not logged in");
}

$username = $_SESSION['logged_in_user'];
$upload_dir = __DIR__ . "/assets/mockups/";
$max_size = 400 * 1024; // 400KB

$allowed_extensions = ['png'];
$max_files_default = 5;
$max_files_override = 10;

// Override logic
$special_users = ['edkeyte', 'adminuser'];
$max_files = in_array($username, $special_users) ? $max_files_override : $max_files_default;

// Count existing mockups
$pattern = $upload_dir . "{$username}_*.png";
$existing_files = glob($pattern);
if (count($existing_files) >= $max_files) {
    exit("Upload limit reached");
}

// Upload checks
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    exit("Upload error");
}

$file = $_FILES['file'];
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

if (!in_array($ext, $allowed_extensions)) {
    exit("Only PNG allowed");
}
if ($file['size'] > $max_size) {
    exit("File too large");
}

// Save file
$new_filename = $username . "_" . uniqid() . ".png";
if (move_uploaded_file($file['tmp_name'], $upload_dir . $new_filename)) {
    echo "success";
} else {
    exit("Upload failed");
}
?>
