<?php
// /elms/coordinator/approval.php
declare(strict_types=1);

require_once __DIR__ . '/../includes/coordinator_auth.php';
require_once __DIR__ . '/../includes/elms_notifications.php';

@date_default_timezone_set('Asia/Colombo');

$db = null;
if (isset($mysqli) && $mysqli instanceof mysqli) {
    $db = $mysqli;
} elseif (isset($conn) && $conn instanceof mysqli) {
    $db = $conn;
}

if (!$db) {
    http_response_code(500);
    exit('Database connection not found.');
}

$db->set_charset('utf8mb4');

if (!function_exists('h')) {
    function h($value): string {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

function ca_table_exists(mysqli $db, string $table): bool {
    $safe = $db->real_escape_string($table);
    $res = $db->query("SHOW TABLES LIKE '{$safe}'");
    $ok = $res && $res->num_rows > 0;
    if ($res) $res->free();
    return $ok;
}

function ca_col_exists(mysqli $db, string $table, string $col): bool {
    $safeTable = preg_replace('/[^a-zA-Z0-9_]/', '', $table);
    $safeCol = $db->real_escape_string($col);
    $res = $db->query("SHOW COLUMNS FROM `{$safeTable}` LIKE '{$safeCol}'");
    $ok = $res && $res->num_rows > 0;
    if ($res) $res->free();
    return $ok;
}

function ca_first_col(mysqli $db, string $table, array $cols): ?string {
    foreach ($cols as $col) {
        if (ca_col_exists($db, $table, $col)) {
            return $col;
        }
    }
    return null;
}

function ca_redirect(string $status): void {
    header("Location: /elms/coordinator/approval.php?{$status}=1");
    exit;
}

$PAGE_TITLE = 'Approval Center';
$ACTIVE = 'approval';

$error = '';
$rows = [];

if (!ca_table_exists($db, 'lms_submissions') || !ca_table_exists($db, 'lms_assessments')) {
    $error = 'Required tables not found.';
} else {
    $hasWorkflow = ca_col_exists($db, 'lms_submissions', 'workflow_status');
    $hasUpdatedAt = ca_col_exists($db, 'lms_submissions', 'updated_at');
    $hasReleasedAt = ca_col_exists($db, 'lms_submissions', 'released_at');
    // Ensure released_at column exists for final result release timestamp
if (!$hasReleasedAt) {
    $db->query("ALTER TABLE lms_submissions ADD COLUMN released_at DATETIME NULL AFTER graded_at");
    $hasReleasedAt = ca_col_exists($db, 'lms_submissions', 'released_at');
}
    $hasFinalScore = ca_col_exists($db, 'lms_submissions', 'final_score');
    $hasFeedback = ca_col_exists($db, 'lms_submissions', 'feedback');
    $hasLectFeedback = ca_col_exists($db, 'lms_submissions', 'lecturer_feedback');

    $feedbackCol = $hasLectFeedback ? 'lecturer_feedback' : ($hasFeedback ? 'feedback' : null);

/* ---------------- POST ACTIONS ---------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $submissionId = (int)($_POST['submission_id'] ?? 0);
    $action = (string)($_POST['action'] ?? '');
    $note = trim((string)($_POST['note'] ?? ''));

    if ($submissionId <= 0 || !$hasWorkflow) {
        ca_redirect('invalid');
    }

    // Load current status first
    $stmt = $db->prepare("
        SELECT id, workflow_status
        FROM lms_submissions
        WHERE id = ?
        LIMIT 1
    ");

    if (!$stmt) {
        $error = 'Status check error: ' . $db->error;
    } else {
        $stmt->bind_param('i', $submissionId);
        $stmt->execute();
        $currentRow = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if (!$currentRow) {
            ca_redirect('invalid');
        }

        $currentStatus = strtolower(trim((string)($currentRow['workflow_status'] ?? '')));

        $reviewStatuses = [
            'under_review',
            'coord_review',
            'coordinator_review',
            'admin_review'
        ];

        $approvedStatuses = [
            'coord_approved',
            'approved'
        ];

        $newStatus = null;
        $allowed = false;

        if ($action === 'approve') {
            $newStatus = 'coord_approved';
            $allowed = in_array($currentStatus, $reviewStatuses, true);
        } elseif ($action === 'release') {
            $newStatus = 'released';
            $allowed = in_array($currentStatus, $approvedStatuses, true);
        } elseif ($action === 'send_back') {
            $newStatus = 'needs_correction';
            $allowed = in_array($currentStatus, $reviewStatuses, true);
        }

        if ($newStatus === null || !$allowed) {
            ca_redirect('invalid');
        }

        $sets = [];
        $types = '';
        $vals = [];

        $sets[] = "workflow_status = ?";
        $types .= 's';
        $vals[] = $newStatus;

        if ($feedbackCol && $note !== '') {
            $sets[] = "{$feedbackCol} = ?";
            $types .= 's';
            $vals[] = $note;
        }

        if ($hasReleasedAt && $newStatus === 'released') {
            $sets[] = "released_at = NOW()";
        }

        if ($hasUpdatedAt) {
            $sets[] = "updated_at = NOW()";
        }

        /*
         * Safe status guard:
         * approve/send_back only from under_review statuses
         * release only from coord_approved/approved statuses
         */
        if ($newStatus === 'released') {
            $guardSql = "LOWER(COALESCE(workflow_status,'')) IN ('coord_approved','approved')";
        } else {
            $guardSql = "LOWER(COALESCE(workflow_status,'')) IN ('under_review','coord_review','coordinator_review','admin_review')";
        }

        $sql = "
            UPDATE lms_submissions
            SET " . implode(', ', $sets) . "
            WHERE id = ?
              AND {$guardSql}
        ";

        $types .= 'i';
        $vals[] = $submissionId;

        $stmt = $db->prepare($sql);

        if (!$stmt) {
            $error = 'Update error: ' . $db->error;
        } else {
            $stmt->bind_param($types, ...$vals);
            $stmt->execute();
            $affected = $stmt->affected_rows;
            $stmt->close();

            if ($affected <= 0) {
    ca_redirect('invalid');
}

/* Notify student after coordinator action */
$notifyStudentId = 0;
$notifyAssessmentTitle = 'Assessment';

$infoStmt = $db->prepare("
    SELECT s.student_id, a.title AS assessment_title
    FROM lms_submissions s
    LEFT JOIN lms_assessments a ON a.id = s.assessment_id
    WHERE s.id = ?
    LIMIT 1
");

if ($infoStmt) {
    $infoStmt->bind_param('i', $submissionId);
    $infoStmt->execute();
    $infoRow = $infoStmt->get_result()->fetch_assoc();
    $infoStmt->close();

    $notifyStudentId = (int)($infoRow['student_id'] ?? 0);
    $notifyAssessmentTitle = (string)($infoRow['assessment_title'] ?? 'Assessment');
}

if ($newStatus === 'released') {
    lms_notify(
        $db,
        'student',
        $notifyStudentId,
        'Result Released',
        'Your result for ' . $notifyAssessmentTitle . ' has been released.',
        '/elms/student/results.php',
        'bi-award',
        'success'
    );
}

if ($newStatus === 'needs_correction') {
    lms_notify(
        $db,
        'student',
        $notifyStudentId,
        'Correction Required',
        'Your submission for ' . $notifyAssessmentTitle . ' needs correction.',
        '/elms/student/assessments/assessments.php',
        'bi-arrow-counterclockwise',
        'warning'
    );
}

if ($newStatus === 'coord_approved') ca_redirect('approved');
if ($newStatus === 'released') ca_redirect('released');
if ($newStatus === 'needs_correction') ca_redirect('sentback');
        }
    }
}

    /* ---------------- LOAD DATA ---------------- */
    $studentTable = ca_table_exists($db, 'studentss')
        ? 'studentss'
        : (ca_table_exists($db, 'students') ? 'students' : null);

    $assessmentTitleCol = ca_first_col($db, 'lms_assessments', ['title', 'name']) ?? 'id';

    $joinStudent = '';
    $studentExpr = "CONCAT('#', s.student_id)";

    if ($studentTable) {
        $studentNameCol = ca_first_col($db, $studentTable, ['full_name', 'name', 'student_name']) ?? 'id';
        $joinStudent = "LEFT JOIN {$studentTable} st ON st.id = s.student_id";
        $studentExpr = "COALESCE(st.`{$studentNameCol}`, CONCAT('#', s.student_id))";
    }

    $scoreExpr = $hasFinalScore ? "s.final_score" : "NULL AS final_score";
    $feedbackExpr = $feedbackCol ? "s.{$feedbackCol} AS feedback" : "'' AS feedback";
    $statusExpr = $hasWorkflow ? "s.workflow_status" : "'under_review' AS workflow_status";

    $dateExpr = ca_col_exists($db, 'lms_submissions', 'graded_at') ? "s.graded_at" :
        ($hasUpdatedAt ? "s.updated_at" :
        (ca_col_exists($db, 'lms_submissions', 'submitted_at') ? "s.submitted_at" : "s.id"));

    $sql = "
        SELECT
            s.id AS submission_id,
            s.student_id,
            s.assessment_id,
            s.batch_id,
            a.`{$assessmentTitleCol}` AS assessment_title,
            {$studentExpr} AS student_name,
            {$scoreExpr},
            {$feedbackExpr},
            {$statusExpr},
            {$dateExpr} AS action_date
        FROM lms_submissions s
        JOIN lms_assessments a ON a.id = s.assessment_id
        {$joinStudent}
        WHERE LOWER(COALESCE(s.workflow_status,'')) IN ('under_review','coord_review','coordinator_review','coord_approved','admin_review')
        ORDER BY s.id DESC
        LIMIT 300
    ";

    $res = $db->query($sql);
    if ($res) {
        $rows = $res->fetch_all(MYSQLI_ASSOC);
        $res->free();
    } else {
        $error = 'Approval SQL error: ' . $db->error;
    }
}

$underReview = 0;
$approved = 0;

foreach ($rows as $r) {
    $st = strtolower((string)($r['workflow_status'] ?? ''));
    if (in_array($st, ['under_review', 'coord_review', 'coordinator_review', 'admin_review'], true)) {
        $underReview++;
    }
    if ($st === 'coord_approved') {
        $approved++;
    }
}

require_once __DIR__ . '/../includes/coordinator_layout_top.php';
?>

<div class="d-flex justify-content-between align-items-start mb-4">
    <div>
        <h1 class="page-title">Approval Center</h1>
        <div class="page-subtitle">Review lecturer marking, approve, send back or release results</div>
    </div>

    <div class="d-flex gap-2">
        <a href="/elms/coordinator/release.php" class="btn btn-light border rounded-4">
            <i class="bi bi-arrow-left me-1"></i> Release Center
        </a>
    </div>
</div>

<?php if ($error): ?>
    <div class="alert alert-warning rounded-4">
        <strong>Notice:</strong> <?= h($error) ?>
    </div>
<?php endif; ?>

<?php if (isset($_GET['approved'])): ?>
    <div class="alert alert-success rounded-4">
        <i class="bi bi-check-circle me-1"></i> Submission approved successfully.
    </div>
<?php endif; ?>

<?php if (isset($_GET['released'])): ?>
    <div class="alert alert-success rounded-4">
        <i class="bi bi-send-check me-1"></i> Result released successfully.
    </div>
<?php endif; ?>


<?php if (isset($_GET['sentback'])): ?>
    <div class="alert alert-warning rounded-4">
        <i class="bi bi-arrow-counterclockwise me-1"></i> Submission sent back for correction.
    </div>
    
<?php endif; ?>
<?php if (isset($_GET['invalid'])): ?>
    <div class="alert alert-danger rounded-4">
        <i class="bi bi-exclamation-triangle me-1"></i>
        Invalid action or this submission status has already changed.
    </div>
<?php endif; ?>

<div class="row g-3 mb-4">
    <div class="col-md-4">
        <div class="eden-card p-3">
            <div class="text-muted small">Under Review</div>
            <div class="fs-3 fw-bold"><?= number_format($underReview) ?></div>
            <i class="bi bi-hourglass-split fs-4 text-danger"></i>
        </div>
    </div>

    <div class="col-md-4">
        <div class="eden-card p-3">
            <div class="text-muted small">Coordinator Approved</div>
            <div class="fs-3 fw-bold"><?= number_format($approved) ?></div>
            <i class="bi bi-check2-circle fs-4 text-danger"></i>
        </div>
    </div>

    <div class="col-md-4">
        <div class="eden-card p-3">
            <div class="text-muted small">Total Review Items</div>
            <div class="fs-3 fw-bold"><?= number_format(count($rows)) ?></div>
            <i class="bi bi-list-check fs-4 text-danger"></i>
        </div>
    </div>
</div>

<div class="eden-card p-3 mb-4">
    <div class="row g-3 align-items-center">
        <div class="col-lg-8">
            <div class="input-group">
                <span class="input-group-text bg-white border-end-0">
                    <i class="bi bi-search"></i>
                </span>
                <input type="text" id="approvalSearch" class="form-control border-start-0" placeholder="Search student, assessment, status...">
            </div>
        </div>

        <div class="col-lg-4">
            <select id="approvalFilter" class="form-select">
                <option value="">All Status</option>
                <option value="under_review">Under Review</option>
                <option value="coord_approved">Approved</option>
            </select>
        </div>
    </div>
</div>

<div class="eden-card overflow-hidden">
    <div class="px-3 py-3 border-bottom bg-white d-flex justify-content-between align-items-center">
        <strong>Lecturer Marking Review</strong>
        <span class="text-muted small">Coordinator Approval Flow</span>
    </div>

    <div class="table-responsive">
        <table class="table table-hover align-middle mb-0" id="approvalTable">
            <thead class="table-light">
                <tr>
                    <th style="width:70px;">ID</th>
                    <th>Student</th>
                    <th>Assessment</th>
                    <th>Batch</th>
                    <th>Score</th>
                    <th>Feedback</th>
                    <th>Status</th>
                    <th>Date</th>
                    <th class="text-end" style="width:260px;">Action</th>
                </tr>
            </thead>

            <tbody>
            <?php if (!$rows): ?>
                <tr>
                    <td colspan="9" class="text-center text-muted py-5">
                        <i class="bi bi-inbox fs-2 d-block mb-2"></i>
                        No approval items found.
                    </td>
                </tr>
            <?php else: ?>
                <?php foreach ($rows as $r): ?>
                    <?php
                        $status = strtolower((string)($r['workflow_status'] ?? ''));
                        $isApproved = $status === 'coord_approved';
                        $isReview = in_array($status, ['under_review', 'coord_review', 'coordinator_review', 'admin_review'], true);
                    ?>

                    <tr data-status="<?= h($status) ?>">
                        <td class="text-muted">#<?= (int)$r['submission_id'] ?></td>

                        <td class="fw-semibold">
                            <?= h($r['student_name'] ?? '-') ?>
                        </td>

                        <td>
                            <div class="fw-bold"><?= h($r['assessment_title'] ?? '-') ?></div>
                            <div class="small text-muted">Assessment ID: <?= (int)$r['assessment_id'] ?></div>
                        </td>

                        <td>
                            <span class="badge text-bg-light border rounded-pill">
                                <?= h((string)($r['batch_id'] ?? '-')) ?>
                            </span>
                        </td>

                        <td>
                            <?php if ($r['final_score'] !== null && $r['final_score'] !== ''): ?>
                                <span class="badge text-bg-primary rounded-pill">
                                    <?= h((string)$r['final_score']) ?>
                                </span>
                            <?php else: ?>
                                <span class="text-muted">Not marked</span>
                            <?php endif; ?>
                        </td>

                        <td style="max-width:260px;">
                            <div class="small text-muted text-truncate">
                                <?= h((string)($r['feedback'] ?? '')) ?>
                            </div>
                        </td>

                        <td>
                            <?php if ($isApproved): ?>
                                <span class="badge text-bg-success rounded-pill">Approved</span>
                            <?php elseif ($isReview): ?>
                                <span class="badge text-bg-warning rounded-pill">Under Review</span>
                            <?php else: ?>
                                <span class="badge text-bg-secondary rounded-pill"><?= h($status) ?></span>
                            <?php endif; ?>
                        </td>

                        <td class="small text-muted">
                            <?= h((string)($r['action_date'] ?? '-')) ?>
                        </td>

                        <td class="text-end">
                            <div class="d-flex gap-1 justify-content-end flex-wrap">
                                <?php if ($isReview): ?>
                                    <form method="post" class="d-inline">
                                        <input type="hidden" name="submission_id" value="<?= (int)$r['submission_id'] ?>">
                                        <button name="action" value="approve" class="btn btn-sm btn-success rounded-pill">
                                            Approve
                                        </button>
                                    </form>

                                    <button type="button"
                                            class="btn btn-sm btn-warning rounded-pill"
                                            data-bs-toggle="modal"
                                            data-bs-target="#sendBackModal<?= (int)$r['submission_id'] ?>">
                                        Send Back
                                    </button>
                                <?php endif; ?>

                                <?php if ($isApproved): ?>
                                    <form method="post" class="d-inline" onsubmit="return confirm('Release this result to student?');">
                                        <input type="hidden" name="submission_id" value="<?= (int)$r['submission_id'] ?>">
                                        <button name="action" value="release" class="btn btn-sm btn-danger rounded-pill">
                                            Release
                                        </button>
                                    </form>
                                <?php endif; ?>
                            </div>

                            <div class="modal fade" id="sendBackModal<?= (int)$r['submission_id'] ?>" tabindex="-1">
                                <div class="modal-dialog modal-dialog-centered">
                                    <form method="post" class="modal-content rounded-4 border-0 shadow">
                                        <input type="hidden" name="submission_id" value="<?= (int)$r['submission_id'] ?>">

                                        <div class="modal-header">
                                            <h5 class="modal-title">Send Back for Correction</h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                        </div>

                                        <div class="modal-body text-start">
                                            <label class="form-label small fw-bold">Correction Note</label>
                                            <textarea name="note" rows="4" class="form-control" placeholder="Enter correction reason..."></textarea>
                                        </div>

                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-light border rounded-4" data-bs-dismiss="modal">Cancel</button>
                                            <button name="action" value="send_back" class="btn btn-warning rounded-4 fw-bold">
                                                Send Back
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const searchInput = document.getElementById('approvalSearch');
    const approvalFilter = document.getElementById('approvalFilter');
    const rows = Array.from(document.querySelectorAll('#approvalTable tbody tr[data-status]'));

    function filterTable() {
        const q = (searchInput.value || '').toLowerCase().trim();
        const st = (approvalFilter.value || '').toLowerCase().trim();

        rows.forEach(row => {
            const text = row.innerText.toLowerCase();
            const rowStatus = (row.dataset.status || '').toLowerCase();

            const matchSearch = q === '' || text.includes(q);
            const matchStatus = st === '' || rowStatus === st;

            row.style.display = (matchSearch && matchStatus) ? '' : 'none';
        });
    }

    searchInput.addEventListener('input', filterTable);
    approvalFilter.addEventListener('change', filterTable);
});
</script>

<?php require_once __DIR__ . '/../includes/coordinator_layout_bottom.php'; ?>