<?php

declare(strict_types=1);

require_once __DIR__ . '/src/database.php';
require_once __DIR__ . '/src/services/job-service.php';

use Notifier\Database;
use Notifier\Services\JobService;

$token = isset($_GET['token']) ? trim((string) $_GET['token']) : '';
$state = 'invalid';
$history = null;
$cancelledCount = 0;
$ui = [
    'icon' => 'bi-check-lg',
    'badge' => 'icon-badge',
    'title' => 'Has completado esta tarea?',
    'body' => 'Si confirmas, todos los recordatorios se pararan.',
    'show_confirm' => true,
];

if ($token !== '' && preg_match('/^[a-f0-9]{32}$/i', $token)) {
    $config = require __DIR__ . '/config.php';
    $database = new Database($config['database']['path'] ?? __DIR__ . '/database.sqlite');
    $pdo = $database->getPdo();
    $jobService = new JobService($pdo);

    $stmt = $pdo->prepare('
        SELECT h.id, h.confirmed_at, n.title as notification_title
        FROM notification_history h
        LEFT JOIN notifications n ON h.notification_id = n.id
        WHERE h.confirm_token = ?
    ');
    $stmt->execute([$token]);
    $history = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($history) {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $pdo->beginTransaction();
            $updateStmt = $pdo->prepare('
                UPDATE notification_history
                SET confirmed_at = datetime("now")
                WHERE id = ? AND confirmed_at IS NULL
            ');
            $updateStmt->execute([$history['id']]);
            $updated = $updateStmt->rowCount() > 0;

            if ($updated) {
                $cancelledCount = $jobService->cancelSubsequentsByHistory((int) $history['id'], 'callback_received');
                $state = 'confirmed';
            } else {
                $state = 'already';
            }
            $pdo->commit();
        } else {
            $state = $history['confirmed_at'] ? 'already' : 'ready';
        }
    }
}

http_response_code($state === 'invalid' ? 404 : 200);

switch ($state) {
    case 'invalid':
        $ui = [
            'icon' => 'bi-x-lg',
            'badge' => 'icon-badge icon-badge-error',
            'title' => 'Enlace no valido',
            'body' => 'Este enlace no es valido o ya no esta disponible.',
            'show_confirm' => false,
        ];
        break;
    case 'already':
        $ui = [
            'icon' => 'bi-check-lg',
            'badge' => 'icon-badge',
            'title' => 'Esta tarea ya fue confirmada',
            'body' => 'No se enviaran mas recordatorios para esta ocurrencia.',
            'show_confirm' => false,
        ];
        break;
    case 'confirmed':
        $ui = [
            'icon' => 'bi-check-lg',
            'badge' => 'icon-badge',
            'title' => 'Confirmacion recibida',
            'body' => 'Listo, detuvimos los recordatorios para esta ocurrencia.',
            'show_confirm' => false,
        ];
        break;
    default:
        break;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Confirm Completion</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Figtree:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        :root {
            --bg: #f8fafc;
            --card: #ffffff;
            --text: #0f172a;
            --muted: #64748b;
            --accent: #4f46e5;
            --border: #e2e8f0;
        }
        body {
            font-family: 'Figtree', sans-serif;
            background: var(--bg);
            color: var(--text);
        }
        .card {
            background: var(--card);
            border: 1px solid var(--border);
            border-radius: 14px;
            box-shadow: 0 16px 36px rgba(15, 23, 42, 0.07);
        }
        .icon-badge {
            background: #e0e7ff;
            color: var(--accent);
        }
        .icon-badge-error {
            background: #fee2e2;
            color: #dc2626;
        }
        .btn-primary {
            background: var(--accent);
            color: #ffffff;
        }
        .btn-primary:hover {
            background: #4338ca;
        }
    </style>
</head>
<body class="min-h-screen flex items-center justify-center px-4 py-10">
    <div class="card w-full max-w-sm p-6">
        <div class="<?= htmlspecialchars($ui['badge'], ENT_QUOTES, 'UTF-8') ?> h-12 w-12 rounded-full flex items-center justify-center text-lg mb-4">
            <i class="bi <?= htmlspecialchars($ui['icon'], ENT_QUOTES, 'UTF-8') ?>"></i>
        </div>
        <h1 class="text-xl font-semibold"><?= htmlspecialchars($ui['title'], ENT_QUOTES, 'UTF-8') ?></h1>
        <p class="text-sm text-slate-500 mt-2"><?= htmlspecialchars($ui['body'], ENT_QUOTES, 'UTF-8') ?></p>

        <?php if (!empty($history['notification_title'])): ?>
            <div class="mt-4 border border-slate-200 rounded-lg px-4 py-3">
                <p class="text-xs text-slate-500">Tarea</p>
                <p class="text-sm font-medium mt-1"><?= htmlspecialchars((string) $history['notification_title'], ENT_QUOTES, 'UTF-8') ?></p>
            </div>
        <?php endif; ?>

        <?php if (!empty($ui['show_confirm'])): ?>
            <form method="POST" class="mt-5">
                <button type="submit" class="btn-primary w-full h-10 rounded-lg text-sm font-semibold flex items-center justify-center gap-2">
                    <i class="bi bi-check-lg"></i>
                    Confirmar
                </button>
            </form>
            <button type="button" onclick="handleClose()" class="w-full h-10 rounded-lg border border-slate-200 text-sm font-medium text-slate-600 mt-3 hover:bg-slate-50 flex items-center justify-center gap-2">
                <i class="bi bi-x-lg"></i>
                Aun no, cierra la pagina
            </button>
        <?php else: ?>
            <button type="button" onclick="handleClose()" class="w-full h-10 rounded-lg border border-slate-200 text-sm font-medium text-slate-600 mt-5 hover:bg-slate-50 flex items-center justify-center gap-2">
                <i class="bi bi-x-lg"></i>
                Cerrar pagina
            </button>
        <?php endif; ?>
    </div>
    <script>
        function handleClose() {
            window.close();
            setTimeout(function () {
                if (window.history.length > 1) {
                    window.history.back();
                }
            }, 150);
        }
    </script>
</body>
</html>
