<?php
require_once '../config/db.php';
require_once '../config/cors.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
    exit;
}

$userId = isset($_POST['user_id']) ? (int) $_POST['user_id'] : 0;
if ($userId <= 0) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid user ID']);
    exit;
}

if (!isset($_FILES['signature']) || $_FILES['signature']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['status' => 'error', 'message' => 'No signature uploaded or upload error']);
    exit;
}

$sigDir = __DIR__ . '/../storage/officers_signature/';
if (!is_dir($sigDir)) {
    mkdir($sigDir, 0755, true);
}

// Optional: remove old signatures to save space
$oldFiles = glob($sigDir . 'officer_' . $userId . '_*');
foreach ($oldFiles as $f) {
    @unlink($f);
}

$ext = pathinfo($_FILES['signature']['name'], PATHINFO_EXTENSION);
if (empty($ext)) {
    $ext = 'png';
}

$fileName = 'officer_' . $userId . '_' . time() . '.' . $ext;
$dest = $sigDir . $fileName;

if (move_uploaded_file($_FILES['signature']['tmp_name'], $dest)) {
    echo json_encode([
        'status' => 'success',
        'message' => 'Signature uploaded successfully',
        'signature_path' => 'storage/officers_signature/' . $fileName
    ]);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Failed to save signature file']);
}
?>