<?php
/**
 * Upload Card Logo API
 * 
 * Handles checking and uploading of the student card logo.
 * Accepts only PNG files and saves it sequentially as card_logo.png.
 */

header('Content-Type: application/json');

session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => '',
    'secure' => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on',
    'httponly' => true,
    'samesite' => 'Lax'
]);
session_start();

if (!isset($_SESSION['userid'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$logoPath = '../images/card_logo.png';

// Check if file exists request
if (isset($_GET['check']) && $_GET['check'] == 1) {
    echo json_encode(['exists' => file_exists($logoPath)]);
    exit();
}

// Upload file request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_FILES['cardLogo']) || $_FILES['cardLogo']['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['success' => false, 'message' => 'براہ کرم صحیح فائل منتخب کریں۔']);
        exit();
    }

    $fileInfo = mime_content_type($_FILES['cardLogo']['tmp_name']);
    if ($fileInfo !== 'image/png') {
        echo json_encode(['success' => false, 'message' => 'صرف PNG تصویر کی اجازت ہے۔']);
        exit();
    }

    if (move_uploaded_file($_FILES['cardLogo']['tmp_name'], $logoPath)) {
        echo json_encode(['success' => true, 'message' => 'لوگو کامیابی سے اپلوڈ ہو گیا۔']);
    } else {
        echo json_encode(['success' => false, 'message' => 'فائل اپلوڈ کرنے میں مسئلہ پیش آیا۔']);
    }
    exit();
}

echo json_encode(['success' => false, 'message' => 'Not a valid request.']);
exit();
