<?php

require_once '../../../config.php';

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



if (!isset($_SESSION['user_id'])) {

    echo json_encode(['success' => false, 'message' => 'Unauthorised']); exit;

}

if (!in_array($_SESSION['role'] ?? '', ['admin', 'director', 'headteacher'])) {

    echo json_encode(['success' => false, 'message' => 'Access denied']); exit;

}



$conn = getDBConnection();

$input = json_decode(file_get_contents('php://input'), true);



$id        = (int) ($input['id'] ?? 0);

$tableType = trim($input['table_type'] ?? '');

$sigData   = $input['signature_data'] ?? '';



if (!$id || !in_array($tableType, ['user', 'staff']) || empty($sigData)) {

    echo json_encode(['success' => false, 'message' => 'Missing required fields']); exit;

}



if (!preg_match('/^data:image\/(png|jpe?g);base64,(.+)$/s', $sigData, $matches)) {

    echo json_encode(['success' => false, 'message' => 'Invalid image format — PNG or JPEG required']); exit;

}



$ext       = ($matches[1] === 'png') ? 'png' : 'jpg';

$imageData = base64_decode(str_replace(' ', '+', $matches[2]));



if ($imageData === false || strlen($imageData) > 2 * 1024 * 1024) {

    echo json_encode(['success' => false, 'message' => 'Invalid image data or file exceeds 2 MB']); exit;

}



// Verify it is actually an image

$tmpFile = tempnam(sys_get_temp_dir(), 'sig_');

file_put_contents($tmpFile, $imageData);

$imgInfo = @getimagesize($tmpFile);

unlink($tmpFile);

if (!$imgInfo) {

    echo json_encode(['success' => false, 'message' => 'Uploaded file is not a valid image']); exit;

}



$uploadDir = __DIR__ . '/../../../uploads/signatures/persistent/';

if (!is_dir($uploadDir)) {

    mkdir($uploadDir, 0755, true);

}



$filename = $tableType . '_' . $id . '_sig.' . $ext;

$filePath = $uploadDir . $filename;

$relPath  = 'uploads/signatures/persistent/' . $filename;



if (file_put_contents($filePath, $imageData) === false) {

    echo json_encode(['success' => false, 'message' => 'Failed to write signature file']); exit;

}

// Drop the stale sibling extension (png <-> jpg) so a subject never keeps two
// signature files, one of which the database no longer references.
$staleExt  = ($ext === 'png') ? 'jpg' : 'png';
$stalePath = $uploadDir . $tableType . '_' . $id . '_sig.' . $staleExt;
if (is_file($stalePath)) {
    @unlink($stalePath);
}



// Ensure columns exist (idempotent)

$conn->query("ALTER TABLE users ADD COLUMN IF NOT EXISTS signature_path VARCHAR(255) NULL DEFAULT NULL");

$conn->query("ALTER TABLE staff ADD COLUMN IF NOT EXISTS signature_path VARCHAR(255) NULL DEFAULT NULL");



if ($tableType === 'user') {

    $stmt = $conn->prepare("UPDATE users SET signature_path = ? WHERE id = ?");

} else {

    $stmt = $conn->prepare("UPDATE staff SET signature_path = ? WHERE id = ?");

}

$stmt->bind_param('si', $relPath, $id);

$ok = $stmt->execute();

$stmt->close();



if (!$ok) {

    echo json_encode(['success' => false, 'message' => 'Database update failed: ' . $conn->error]); exit;

}



// Activity logging is best-effort: a logging failure must never abort the
// response, or the client sees invalid JSON for a save that actually succeeded.
try {
    logActivity($conn, $_SESSION['user_id'], 'update_signature', $tableType . ' id=' . $id . ' signature updated');
} catch (Throwable $e) {
    error_log('save_persistent_signature: logActivity failed - ' . $e->getMessage());
}

$conn->close();

echo json_encode(['success' => true, 'message' => 'Signature saved successfully', 'data' => ['path' => $relPath]]);

