<?php
session_start();
header('Content-Type: application/json');
ini_set('display_errors', 1);
 
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;
}

// Allowed MIME types and extensions for photos
$allowedMimes = [
    'image/jpeg',        // .jpg, .jpeg
    'image/jpg',         // sometimes reported separately
    'image/png',         // .png
    'application/pdf'    // .pdf
];

$allowedExtensions = ['jpg', 'jpeg', 'png', 'pdf'];

// Upload directory
$uploadDir = __DIR__ . '/uploads/photos/';
if (!is_dir($uploadDir) && !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 for upload
if (
    !isset($_FILES['photo']) ||
    $_FILES['photo']['error'] !== UPLOAD_ERR_OK
) {
    echo json_encode([
        'success'    => false,
        'message'    => 'No photo uploaded or upload error.',
        'error_code' => $_FILES['photo']['error'] ?? null
    ]);
    exit;
}

$fileTmp       = $_FILES['photo']['tmp_name'];
$fileName      = basename($_FILES['photo']['name']);
$fileSize      = $_FILES['photo']['size'];
$fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

// Validate extension
if (!in_array($fileExtension, $allowedExtensions, true)) {
    echo json_encode(['success' => false, 'message' => 'Invalid file extension. Only JPG , PNG , JPEG, PDF allowed.']);
    exit;
}

// Determine MIME type
if (function_exists('finfo_open')) {
    $finfo    = finfo_open(FILEINFO_MIME_TYPE);
    $fileType = finfo_file($finfo, $fileTmp);
    finfo_close($finfo);
} else {
    $fileType = $_FILES['photo']['type'];
}

// Validate MIME type
if (!in_array($fileType, $allowedMimes, true)) {
    echo json_encode(['success' => false, 'message' => 'Invalid file type. O Only JPG , PNG , JPEG, PDF allowed']);
    exit;
}

// Validate file size (max 10MB)
if ($fileSize > 20 * 1024 * 1024) {
    echo json_encode(['success' => false, 'message' => 'Photo size exceeds 10MB limit.']);
    exit;
}

// Generate a clean filename: userId_timestamp.extension
$userId   = $_SESSION['user_id'];
$timestamp = time();
$safeName  = $userId . '_' . $timestamp . '.' . $fileExtension;
$destination = $uploadDir . $safeName;

// Move the uploaded photo
if (!move_uploaded_file($fileTmp, $destination)) {
    echo json_encode(['success' => false, 'message' => 'Failed to move uploaded photo.']);
    exit;
}

// Success response
echo json_encode([
    'success'  => true,
    'message'  => 'Photo uploaded successfully!',
    'filename' => $safeName
]);
?>