<?php
/**
 * Upload Signature API
 * 
 * Handles checking and uploading of the Muhtamim signature.
 * Accepts only PNG files and saves it as Signature.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();
}

$signaturePath = '../images/Signature.png';

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

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

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

    if (move_uploaded_file($_FILES['signatureImage']['tmp_name'], $signaturePath)) {
        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();
