<?php
require_once __DIR__ . '/header.php';
require_login();

$user    = current_user();
$isSuper = perms_is_super($user);
$canManage = perms_can_manage($user);
$attemptId = v_int($_GET['id'] ?? 0, 1);

if ($attemptId <= 0) {
    echo '<div class="alert alert-danger">Invalid attempt ID.</div>';
    require __DIR__ . '/footer.php';
    exit;
}

$stmt = $pdo->prepare("
    SELECT a.*, c.candidate_number, c.name AS candidate_name, c.barcode, c.facility_id,
           f.name AS form_name, u.full_name AS examiner_name, u.id AS examiner_id
    FROM attempts a
    JOIN candidates c ON a.candidate_id = c.id
    JOIN forms f      ON a.form_id      = f.id
    JOIN users u      ON a.examiner_id  = u.id
    WHERE a.id = ? AND a.deleted_at IS NULL
");
$stmt->execute([$attemptId]);
$attempt = $stmt->fetch();

if (!$attempt) {
    echo '<div class="alert alert-danger">Attempt not found.</div>';
    require __DIR__ . '/footer.php';
    exit;
}
// Permission: super_admin OR original examiner OR coordinator of the candidate's facility
$canEditThis = $isSuper
    || (int)$user['id'] === (int)$attempt['examiner_id']
    || ($canManage && (int)$user['facility_id'] === (int)$attempt['facility_id']);
if (!$canEditThis) {
    echo '<div class="alert alert-danger">You do not have permission to edit this attempt.</div>';
    require __DIR__ . '/footer.php';
    exit;
}

$itemStmt = $pdo->prepare('SELECT * FROM form_items WHERE form_id = ? ORDER BY sort_order');
$itemStmt->execute([$attempt['form_id']]);
$formItems = $itemStmt->fetchAll();

$aiStmt = $pdo->prepare('SELECT * FROM attempt_items WHERE attempt_id = ?');
$aiStmt->execute([$attemptId]);
$attemptItems = $aiStmt->fetchAll();
$map = [];
foreach ($attemptItems as $ai) $map[$ai['form_item_id']] = $ai;

function get_bands(PDO $pdo, int $formId): array {
    $s = $pdo->prepare('SELECT * FROM grade_bands WHERE form_id = ? ORDER BY sort_order');
    $s->execute([$formId]);
    return $s->fetchAll();
}
function pick_grade(array $bands, float $p): string {
    foreach ($bands as $b) {
        if ($p >= $b['min_percent'] && $p <= $b['max_percent']) return $b['label'];
    }
    return 'Uncategorised';
}

$msg = '';
$err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_require();

    $stationName   = v_clean_string($_POST['station_name'] ?? '', 100);
    $globalComment = v_clean_string($_POST['global_comment'] ?? '', 2000);
    $scores        = $_POST['score'] ?? [];
    $comments      = $_POST['item_comment'] ?? [];

    $total = 0; $maxTotal = 0;
    foreach ($formItems as $it) {
        $max = (int)$it['max_score'];
        $maxTotal += $max;
        $val = v_int($scores[$it['id']] ?? 0, 0, $max, 0);
        $total += $val;
    }
    $percent = $maxTotal > 0 ? round(($total / $maxTotal) * 100, 2) : 0;
    $bands = get_bands($pdo, (int)$attempt['form_id']);
    $grade = pick_grade($bands, $percent);

    try {
        $pdo->beginTransaction();
        $pdo->prepare('UPDATE attempts SET station_name=?, total_score=?, max_score=?, percentage=?, final_grade=?, global_comment=? WHERE id=?')
            ->execute([$stationName, $total, $maxTotal, $percent, $grade, $globalComment, $attemptId]);

        $pdo->prepare('DELETE FROM attempt_items WHERE attempt_id = ?')->execute([$attemptId]);
        $ins = $pdo->prepare('INSERT INTO attempt_items (attempt_id, form_item_id, score, comment) VALUES (?, ?, ?, ?)');
        foreach ($formItems as $it) {
            $max = (int)$it['max_score'];
            $val = v_int($scores[$it['id']] ?? 0, 0, $max, 0);
            $cmt = v_clean_string($comments[$it['id']] ?? '', 1000);
            $ins->execute([$attemptId, $it['id'], $val, $cmt]);
        }
        $pdo->commit();

        audit_log($pdo, 'attempt_edit', [
            'attempt_id' => $attemptId,
            'total'      => $total,
            'percentage' => $percent,
        ]);

        $attempt['station_name']   = $stationName;
        $attempt['total_score']    = $total;
        $attempt['max_score']      = $maxTotal;
        $attempt['percentage']     = $percent;
        $attempt['final_grade']    = $grade;
        $attempt['global_comment'] = $globalComment;

        $aiStmt->execute([$attemptId]);
        $attemptItems = $aiStmt->fetchAll();
        $map = [];
        foreach ($attemptItems as $ai) $map[$ai['form_item_id']] = $ai;

        $msg = 'Attempt updated successfully.';
    } catch (Throwable $e) {
        $pdo->rollBack();
        $err = 'Could not save changes.';
        error_log('attempt_edit: ' . $e->getMessage());
    }
}
?>
<h2>Edit Attempt #<?php echo (int)$attempt['id']; ?></h2>

<?php if ($msg): ?><div class="alert alert-success"><?php echo h($msg); ?></div><?php endif; ?>
<?php if ($err): ?><div class="alert alert-danger"><?php echo h($err); ?></div><?php endif; ?>

<p>
    <strong>Candidate:</strong> <?php echo h($attempt['candidate_number'] . ' – ' . $attempt['candidate_name']); ?><br>
    <strong>Barcode:</strong> <code><?php echo h($attempt['barcode']); ?></code><br>
    <strong>Form:</strong> <?php echo h($attempt['form_name']); ?><br>
    <strong>Examiner:</strong> <?php echo h($attempt['examiner_name']); ?><br>
    <strong>Created at:</strong> <?php echo h($attempt['created_at']); ?>
</p>

<form method="post">
    <?php echo csrf_field(); ?>
    <div class="field mb-2">
        <label>Station Name</label>
        <input type="text" name="station_name" value="<?php echo h($attempt['station_name']); ?>">
    </div>

    <div class="table-wrap">
    <table class="data">
        <thead><tr><th>#</th><th>Item</th><th>Max</th><th>Score</th><th>Comment</th></tr></thead>
        <tbody>
        <?php $i=1; foreach ($formItems as $it):
            $ai = $map[$it['id']] ?? null;
            $curScore   = $ai ? (int)$ai['score']   : 0;
            $curComment = $ai ? $ai['comment'] : '';
        ?>
            <tr>
                <td data-label="#"><?php echo $i++; ?></td>
                <td data-label="Item"><?php echo nl2br(h($it['label'])); ?></td>
                <td data-label="Max" class="num"><?php echo (int)$it['max_score']; ?></td>
                <td data-label="Score">
                    <input type="number" name="score[<?php echo (int)$it['id']; ?>]" min="0" max="<?php echo (int)$it['max_score']; ?>" value="<?php echo $curScore; ?>" required style="max-width:90px;">
                </td>
                <td data-label="Comment">
                    <?php if ($it['has_comment']): ?>
                        <input type="text" name="item_comment[<?php echo (int)$it['id']; ?>]" value="<?php echo h($curComment); ?>">
                    <?php else: ?>
                        <span class="muted">—</span>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>

    <div class="field mt-2">
        <label>Global Comment</label>
        <textarea name="global_comment" rows="3"><?php echo h($attempt['global_comment']); ?></textarea>
    </div>

    <button type="submit" class="btn btn-primary mt-2">Save Changes</button>
    <a href="export_grades.php" class="btn">Back to Grades</a>
</form>

<p class="mt-2">
    <strong>Current total:</strong> <?php echo (int)$attempt['total_score'] . ' / ' . (int)$attempt['max_score']; ?>
    (<?php echo h($attempt['percentage']); ?>%) – <strong>Grade:</strong> <?php echo h($attempt['final_grade']); ?>
</p>

<?php require __DIR__ . '/footer.php'; ?>
