<?php

use Carbon\Carbon;
use Mtc\Shop\Assessment\Assessment;
use Mtc\Shop\Assessment\Answer;

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';

$page_meta['title'] = 'Draft Assessments';

$errors = [];
$success = '';

$expiryDays = Assessment::getDraftExpiryDays();

// Handle actions - Only POST requests with valid CSRF token
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_REQUEST['action'])) {
    // Validate CSRF token
    if (empty($_REQUEST['csrf_token']) || $_REQUEST['csrf_token'] !== $_SESSION['csrf_token']) {
        $errors[] = 'Invalid CSRF token. Please try again.';
    } else {
        if ($_REQUEST['action'] === 'delete' && is_numeric($_REQUEST['delete_id'])) {
            $draft = Assessment::query()->find($_REQUEST['delete_id']);
            if ($draft && !$draft->is_completed) {
                $draft->answers()->delete();
                $draft->delete();
                $success = 'Draft assessment deleted successfully.';
            } else {
                $errors[] = 'Draft assessment not found or already completed.';
            }
        }

        if ($_REQUEST['action'] === 'clear_expired') {
            $expiredIds = Assessment::query()
                ->draft()
                ->where('updated_at', '<', Carbon::now()->subDays($expiryDays))
                ->pluck('id');

            if ($expiredIds->isNotEmpty()) {
                $answersDeleted = Answer::whereIn('assessment_id', $expiredIds)->delete();
                $draftsDeleted = Assessment::whereIn('id', $expiredIds)->delete();
                $success = "Cleared {$draftsDeleted} expired draft(s) and {$answersDeleted} answer(s).";
            } else {
                $success = 'No expired drafts found.';
            }
        }

        if ($_REQUEST['action'] === 'clear_all') {
            $allDraftIds = Assessment::query()
                ->draft()
                ->pluck('id');

            if ($allDraftIds->isNotEmpty()) {
                $answersDeleted = Answer::whereIn('assessment_id', $allDraftIds)->delete();
                $draftsDeleted = Assessment::whereIn('id', $allDraftIds)->delete();
                $success = "Cleared {$draftsDeleted} draft(s) and {$answersDeleted} answer(s).";
            } else {
                $success = 'No draft assessments found.';
            }
        }
    }
}

// Generate CSRF token if not already in session
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Fetch drafts with relationships
$drafts = Assessment::query()
    ->with(['form', 'member'])
    ->draft()
    ->orderBy('updated_at', 'desc')
    ->get();

$expiredCount = $drafts->filter(function ($draft) {
    return $draft->isExpired();
})->count();

require_once $path . 'core/admin/templates/adminheader.html.php';

?>
<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <li><a href="/shop/admin/assessment/manage.forms.php">Assessment Forms</a> /</li>
    <li class="end">Draft Assessments</li>
</ul>

<h1>Draft Assessments</h1>
<?php

include __DIR__ . '/tabnav.php';

if (count($errors) > 0) { showerrors($errors); }

if (!empty($success)) {
    ?>
    <div class="el" style="background: #d4edda; border: 1px solid #c3e6cb; color: #155724; padding: 12px 16px; border-radius: 4px; margin-bottom: 20px;">
        <?= htmlspecialchars($success); ?>
    </div>
    <?php
}

?>

<div class="el" style="margin-bottom: 20px;">
    <p style="margin: 0 0 10px;">
        <strong><?= $drafts->count(); ?></strong> draft assessment(s) total.
        <?php if ($expiredCount > 0) { ?>
            <strong><?= $expiredCount; ?></strong> expired (older than <?= $expiryDays; ?> days).
        <?php } ?>
        Draft expiry is set to <strong><?= $expiryDays; ?></strong> day(s).
    </p>
    <?php if ($expiredCount > 0) { ?>
        <form method="POST" style="display: inline;" onsubmit="return confirm('Are you sure you want to delete all expired draft assessments? This action cannot be undone.');">
            <input type="hidden" name="action" value="clear_expired" />
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']); ?>" />
            <button type="submit" class="btn alert" title="Delete all expired draft assessments">Clear Expired Drafts (<?= $expiredCount; ?>)</button>
        </form>
    <?php } ?>
    <?php if ($drafts->count() > 0) { ?>
        <form method="POST" style="display: inline; margin-left: 8px;" onsubmit="return confirm('Are you sure you want to delete ALL draft assessments? This cannot be undone.');">
            <input type="hidden" name="action" value="clear_all" />
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']); ?>" />
            <button type="submit" class="btn alert" title="Delete all draft assessments">Clear All Drafts</button>
        </form>
    <?php } ?>
</div>

<?php

if ($drafts->isNotEmpty()) {
    ?>
    <table class="manage-items">
        <tr>
            <th>ID</th>
            <th>Form</th>
            <th>Member</th>
            <th>Last Updated</th>
            <th>Expires</th>
            <th>Status</th>
            <th class="center">Delete</th>
        </tr>
        <tbody class="tabular">
        <?php
        foreach ($drafts as $draft) {
            $memberName = 'Unknown';
            if ($draft->member && $draft->member->addressBilling) {
                $memberName = trim($draft->member->addressBilling->firstname . ' ' . $draft->member->addressBilling->lastname);
            }
            if ($draft->member) {
                $memberName .= ' (' . $draft->member->email . ')';
            }

            $expiresAt = $draft->getExpiresAt();
            $isExpired = $draft->isExpired();
            ?>
            <tr>
                <td><?= $draft->id; ?></td>
                <td><?= htmlspecialchars($draft->form->name ?? 'Unknown form'); ?></td>
                <td><?= htmlspecialchars($memberName); ?></td>
                <td><?= Carbon::parse($draft->updated_at)->format('j M Y, H:i'); ?></td>
                <td><?= $expiresAt->format('j M Y'); ?></td>
                <td>
                    <?php if ($isExpired) { ?>
                        <span style="color: #ce2b2b; font-weight: bold;">Expired</span>
                    <?php } else { ?>
                        <span style="color: #5aaa23;">Active</span>
                    <?php } ?>
                </td>
                <td class="center">
                    <form method="POST" style="display: inline;" onsubmit="return confirm('Are you sure you want to delete this draft assessment? This action cannot be undone.');">
                        <input type="hidden" name="action" value="delete" />
                        <input type="hidden" name="delete_id" value="<?= $draft->id; ?>" />
                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']); ?>" />
                        <button type="submit" class="alert picto error" title="Delete this draft assessment" style="background: none; border: none; cursor: pointer; padding: 0;"><i class="fa fa-times-circle"></i></button>
                    </form>
                </td>
            </tr>
            <?php
        }
        ?>
        </tbody>
    </table>
    <?php
} else {
    ?>
    <p>No draft assessments found.</p>
    <?php
}

require_once $path . 'core/admin/templates/adminfooter.html.php';
