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

use App\Core\Auth;
use App\Core\Database;
use App\Core\Response;

$user = Auth::requireUser();
if (!Auth::hasPermission('members.view', $user) && !Auth::hasPermission('attendance.manage', $user) && !Auth::hasPermission('walks.view_all', $user) && (($user['role_name'] ?? '') !== 'super_admin')) {
    Response::error('You do not have permission to view signed waivers.', 403);
}

$pdo = Database::connection();
$input = request_input();
$action = (string)($input['action'] ?? 'list');

function pyrk_waiver_signature_select(bool $includeSignature = false): string
{
    $signatureField = $includeSignature ? 'ws.signature_data,' : 'NULL AS signature_data,';
    return 'SELECT
        ws.id,
        ws.walk_id,
        ws.user_id,
        ws.waiver_template_id,
        ws.signed_name,
        ' . $signatureField . '
        ws.accepted_terms,
        ws.ip_address,
        ws.device_info,
        ws.signed_at,
        ws.created_at,
        u.full_name AS member_name,
        u.email AS member_email,
        u.mobile AS member_mobile,
        u.status AS member_status,
        w.title AS walk_title,
        w.walk_date,
        w.start_time,
        w.expected_finish_time,
        w.status AS walk_status,
        r.route_name,
        r.total_km,
        wt.title AS waiver_title,
        wt.version AS waiver_version,
        wt.body_html AS waiver_body_html
    FROM waiver_signatures ws
    JOIN users u ON u.id = ws.user_id
    JOIN walks w ON w.id = ws.walk_id
    LEFT JOIN routes r ON r.id = w.route_id
    LEFT JOIN waiver_templates wt ON wt.id = ws.waiver_template_id';
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && $action === 'stats') {
    $total = (int)$pdo->query('SELECT COUNT(*) FROM waiver_signatures WHERE accepted_terms = 1')->fetchColumn();
    $todayStmt = $pdo->query('SELECT COUNT(*) FROM waiver_signatures WHERE accepted_terms = 1 AND DATE(signed_at) = CURDATE()');
    $today = (int)$todayStmt->fetchColumn();
    $walks = (int)$pdo->query('SELECT COUNT(DISTINCT walk_id) FROM waiver_signatures WHERE accepted_terms = 1')->fetchColumn();
    $members = (int)$pdo->query('SELECT COUNT(DISTINCT user_id) FROM waiver_signatures WHERE accepted_terms = 1')->fetchColumn();
    Response::ok(['stats' => ['total' => $total, 'today' => $today, 'walks' => $walks, 'members' => $members]]);
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && $action === 'walks') {
    $stmt = $pdo->query('SELECT w.id, w.title, w.walk_date, w.start_time, r.route_name,
            (SELECT COUNT(*) FROM waiver_signatures ws WHERE ws.walk_id = w.id AND ws.accepted_terms = 1) AS signed_count
        FROM walks w
        LEFT JOIN routes r ON r.id = w.route_id
        ORDER BY w.walk_date DESC, w.start_time DESC, w.id DESC
        LIMIT 300');
    Response::ok(['walks' => $stmt->fetchAll()]);
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && $action === 'detail') {
    $id = (int)($input['id'] ?? 0);
    if ($id <= 0) Response::error('Missing waiver id.');

    $stmt = $pdo->prepare(pyrk_waiver_signature_select(true) . ' WHERE ws.id = ? AND ws.accepted_terms = 1 LIMIT 1');
    $stmt->execute([$id]);
    $waiver = $stmt->fetch();
    if (!$waiver) Response::error('Signed waiver not found.', 404);

    Response::ok(['waiver' => $waiver]);
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && $action === 'list') {
    $where = ['ws.accepted_terms = 1'];
    $params = [];

    $walkId = (int)($input['walk_id'] ?? 0);
    if ($walkId > 0) {
        $where[] = 'ws.walk_id = ?';
        $params[] = $walkId;
    }

    $userId = (int)($input['user_id'] ?? 0);
    if ($userId > 0) {
        $where[] = 'ws.user_id = ?';
        $params[] = $userId;
    }

    $q = trim((string)($input['q'] ?? ''));
    if ($q !== '') {
        $where[] = '(u.full_name LIKE ? OR u.email LIKE ? OR u.mobile LIKE ? OR w.title LIKE ? OR r.route_name LIKE ? OR ws.signed_name LIKE ?)';
        $like = '%' . $q . '%';
        array_push($params, $like, $like, $like, $like, $like, $like);
    }

    $limit = (int)($input['limit'] ?? 100);
    if ($limit < 20) $limit = 20;
    if ($limit > 300) $limit = 300;

    $sql = pyrk_waiver_signature_select(false) . ' WHERE ' . implode(' AND ', $where) . ' ORDER BY ws.signed_at DESC, ws.id DESC LIMIT ' . $limit;
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

    Response::ok(['waivers' => $stmt->fetchAll()]);
}

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