<?php
session_start();
header('Content-Type: application/json');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

date_default_timezone_set('Asia/Kolkata');

// Ensure user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access.']);
    exit;
}

// Define upload path
$uploadDir = 'uploads/forms/';
if (!is_dir($uploadDir)) {
    if (!mkdir($uploadDir, 0777, true)) {
        echo json_encode(['success' => false, 'message' => 'Failed to create upload directory.']);
        exit;
    }
}

if (!is_writable($uploadDir)) {
    echo json_encode(['success' => false, 'message' => 'Upload directory is not writable.']);
    exit;
}

// Check uploaded file
if (!isset($_FILES['upload_file']) || $_FILES['upload_file']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['success' => false, 'message' => 'No file uploaded or upload error.']);
    exit;
}

// Process file
$fileTmp       = $_FILES['upload_file']['tmp_name'];
$fileName      = $_FILES['upload_file']['name'];
$fileType = $_FILES['upload_file']['type'];
$fileSize      = $_FILES['upload_file']['size'];
$fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

// Allowed types
$allowedExtensions = ['jpg', 'jpeg', 'png', 'pdf'];
if (!in_array($fileExtension, $allowedExtensions)) {
    echo json_encode(['success' => false, 'message' => 'Invalid file type. Allowed: jpg, jpeg, png, pdf.']);
    exit;
}

// Max size check (50MB)
if ($fileSize > 50 * 1024 * 1024) {
    echo json_encode(['success' => false, 'message' => 'File size exceeds 50MB limit.']);
    exit;
}

// Save file
$userId      = $_SESSION['user_id'];
$timestamp   = time();
$safeName    = $userId . '_' . $timestamp . '.' . $fileExtension;
$destination = $uploadDir . $safeName;

if (move_uploaded_file($fileTmp, $destination)) {
    echo json_encode(['success' => true, 'message' => 'File uploaded successfully.', 'filename' => $safeName]);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to move uploaded file.']);
}
?>
