<?php
require __DIR__ . '/bootstrap.php';

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\Database;
use App\Core\Response;
use App\Services\AttendanceService;

$pdo = Database::connection();
$input = request_input();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $template = $pdo->query('SELECT id, title, body_html, version FROM waiver_templates WHERE is_active = 1 ORDER BY version DESC LIMIT 1')->fetch();

    $signature = null;
    $user = Auth::user();
    $walkId = (int)($input['walk_id'] ?? 0);

    if ($user && $walkId > 0) {
        $stmt = $pdo->prepare('SELECT id, signed_name, signature_data, signed_at, accepted_terms FROM waiver_signatures WHERE walk_id = ? AND user_id = ? AND accepted_terms = 1 ORDER BY signed_at DESC, id DESC LIMIT 1');
        $stmt->execute([$walkId, (int)$user['id']]);
        $row = $stmt->fetch();
        if ($row) {
            $signature = [
                'id' => (int)$row['id'],
                'signed_name' => $row['signed_name'],
                'signature_data' => $row['signature_data'] ?? '',
                'signed_at' => $row['signed_at'],
                'accepted_terms' => (int)$row['accepted_terms'],
                'is_signed' => true,
            ];
        }
    }

    Response::ok(['template' => $template, 'signature' => $signature, 'is_signed' => $signature !== null]);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user = Auth::requireUser();
    Csrf::validateFromRequest();
    if (empty($input['walk_id']) || empty($input['signed_name'])) Response::error('walk_id and signed_name are required.');

    $walkId = (int)$input['walk_id'];
    $already = $pdo->prepare('SELECT id, signed_name, signed_at FROM waiver_signatures WHERE walk_id = ? AND user_id = ? AND accepted_terms = 1 LIMIT 1');
    $already->execute([$walkId, (int)$user['id']]);
    $existing = $already->fetch();

    if ($existing) {
        Response::error('Waiver is already signed. Signature is locked and cannot be cleared or changed.', 409, [
            'signature' => [
                'id' => (int)$existing['id'],
                'signed_name' => $existing['signed_name'],
                'signed_at' => $existing['signed_at'],
                'is_signed' => true,
            ],
        ]);
    }

    $signatureData = trim((string)($input['signature_data'] ?? ''));
    if ($signatureData === '') Response::error('Please draw your digital signature before signing the waiver.');
    if (!preg_match('/^data:image\/(png|jpeg);base64,/', $signatureData)) Response::error('Invalid digital signature format.');
    if (strlen($signatureData) > 1000000) Response::error('Digital signature image is too large.');

    (new AttendanceService())->signWaiver($walkId, (int)$user['id'], trim($input['signed_name']), $signatureData);
    Response::ok(['signature' => ['signed_name' => trim($input['signed_name']), 'signed_at' => date('Y-m-d H:i:s'), 'is_signed' => true, 'signature_data' => $signatureData]], 'Waiver signed. Signature is now locked.');
}

Response::error('Unsupported waivers action.', 404);
