<?php

if (session_status() === PHP_SESSION_NONE) { session_start(); }

if (!isset($_SESSION['user_id'])) { header('Location: ../../index.php'); exit; }

if (!in_array($_SESSION['role'] ?? '', ['admin', 'director', 'headteacher'])) {

    header('Location: ../../dashboard.php?error=access_denied'); exit;

}



require_once '../../config.php';

$conn = getDBConnection();



// Ensure columns exist (safe to run on every page load)

$conn->query("ALTER TABLE users ADD COLUMN IF NOT EXISTS signature_path VARCHAR(255) NULL DEFAULT NULL");

$conn->query("ALTER TABLE staff ADD COLUMN IF NOT EXISTS signature_path VARCHAR(255) NULL DEFAULT NULL");



// Director

$director = null;

$r = $conn->query("SELECT id, full_name, signature_path FROM users WHERE role = 'director' ORDER BY id LIMIT 1");

if ($r) $director = $r->fetch_assoc();



// Headteacher

$headteacher = null;

$r = $conn->query("SELECT id, full_name, signature_path FROM users WHERE role = 'headteacher' ORDER BY id LIMIT 1");

if ($r) $headteacher = $r->fetch_assoc();



// Class teachers assigned to active classes (may appear more than once if assigned to multiple classes)

$classTeachers = [];

$r = $conn->query("

    SELECT st.id, st.full_name, st.signature_path,

           GROUP_CONCAT(c.class_name ORDER BY c.class_name SEPARATOR ', ') AS classes

    FROM staff st

    JOIN classes c ON c.class_teacher_id = st.id

    WHERE c.is_active = 1

    GROUP BY st.id, st.full_name, st.signature_path

    ORDER BY st.full_name

");

if ($r) { while ($row = $r->fetch_assoc()) $classTeachers[] = $row; }



$conn->close();

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Report Card Signatures - EduTrack PRO</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <link rel="stylesheet" href="../../css/style.css">

    <style>

        .sig-preview-box {

            min-height: 70px;

            border: 2px dashed #dee2e6;

            border-radius: 6px;

            display: flex;

            align-items: center;

            justify-content: center;

            background: #fafafa;

            padding: 8px;

        }

        .sig-preview-box img { max-height: 60px; }

        .sig-status-none  { border-color: #ffc107; background: #fffbf0; }

        .sig-status-set   { border-color: #198754; background: #f0fff4; }

        #sigPadCanvas { touch-action: none; }

    </style>

</head>

<body>

<div class="wrapper">

    <nav id="sidebar" class="sidebar">

        <?php echo buildSidebar('modules/reports/signatures.php'); ?>

    </nav>



    <div class="main-content">

        <header class="header">

            <button class="btn-toggle" id="sidebarToggle"><i class="fas fa-bars"></i></button>

            <div class="header-right">

                <div class="dropdown">

                    <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">

                        <i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars((string)($_SESSION['full_name'] ?? '')); ?>

                    </button>

                    <ul class="dropdown-menu dropdown-menu-end">

                        <li><a class="dropdown-item" href="../../settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>

                        <li><hr class="dropdown-divider"></li>

                        <li><a class="dropdown-item" href="../../logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>

                    </ul>

                </div>

            </div>

        </header>



        <main class="content">

            <div class="content-header">

                <h2><i class="fas fa-signature me-2"></i>Report Card Signatures</h2>

                <p>Upload or draw persistent signatures — they auto-appear on every terminal report card without manual signing.</p>

                <a href="index.php" class="btn btn-sm btn-outline-secondary" style="position:absolute;right:20px;top:20px;">

                    <i class="fas fa-arrow-left me-1"></i>Back to Reports

                </a>

            </div>



            <div class="alert alert-info d-flex align-items-start gap-2 mb-4">

                <i class="fas fa-info-circle mt-1"></i>

                <div>

                    <strong>How it works:</strong> Upload or draw each signatory's signature once. It will automatically appear on

                    <strong>Print Report</strong>, <strong>Download PDF</strong>, and the <strong>report preview</strong> for every student —

                    no duplicate signing needed. If a signature is not uploaded, the report shows an empty line as a fallback.

                </div>

            </div>



            <!-- Institution signatories -->

            <div class="card mb-4">

                <div class="card-header bg-white">

                    <h5 class="mb-0"><i class="fas fa-building me-2 text-primary"></i>Institution Signatories</h5>

                </div>

                <div class="card-body">

                    <div class="row g-4">



                        <!-- Director -->

                        <div class="col-md-6">

                            <div class="card h-100">

                                <div class="card-header bg-light fw-semibold">

                                    <i class="fas fa-user-tie me-2"></i>Director

                                </div>

                                <div class="card-body text-center">

                                    <?php if ($director): ?>

                                        <p class="text-muted small mb-3"><?php echo htmlspecialchars($director['full_name']); ?></p>

                                        <div class="sig-preview-box <?php echo !empty($director['signature_path']) ? 'sig-status-set' : 'sig-status-none'; ?> mb-3"

                                             id="preview-director">

                                            <?php if (!empty($director['signature_path']) && file_exists('../../' . $director['signature_path'])): ?>

                                                <img src="../../<?php echo htmlspecialchars($director['signature_path']); ?>?t=<?php echo time(); ?>"

                                                     alt="Director signature">

                                            <?php else: ?>

                                                <span class="text-muted small"><i class="fas fa-pen me-1"></i>No signature on file</span>

                                            <?php endif; ?>

                                        </div>

                                        <button class="btn btn-primary btn-sm"

                                                onclick="openModal('director', <?php echo (int)$director['id']; ?>, 'user')">

                                            <i class="fas fa-pen me-1"></i>

                                            <?php echo !empty($director['signature_path']) ? 'Update Signature' : 'Add Signature'; ?>

                                        </button>

                                    <?php else: ?>

                                        <p class="text-muted">No Director account found. Create one in User Management first.</p>

                                    <?php endif; ?>

                                </div>

                            </div>

                        </div>



                        <!-- Headteacher -->

                        <div class="col-md-6">

                            <div class="card h-100">

                                <div class="card-header bg-light fw-semibold">

                                    <i class="fas fa-user-graduate me-2"></i>Head Teacher

                                </div>

                                <div class="card-body text-center">

                                    <?php if ($headteacher): ?>

                                        <p class="text-muted small mb-3"><?php echo htmlspecialchars($headteacher['full_name']); ?></p>

                                        <div class="sig-preview-box <?php echo !empty($headteacher['signature_path']) ? 'sig-status-set' : 'sig-status-none'; ?> mb-3"

                                             id="preview-headteacher">

                                            <?php if (!empty($headteacher['signature_path']) && file_exists('../../' . $headteacher['signature_path'])): ?>

                                                <img src="../../<?php echo htmlspecialchars($headteacher['signature_path']); ?>?t=<?php echo time(); ?>"

                                                     alt="Head Teacher signature">

                                            <?php else: ?>

                                                <span class="text-muted small"><i class="fas fa-pen me-1"></i>No signature on file</span>

                                            <?php endif; ?>

                                        </div>

                                        <button class="btn btn-primary btn-sm"

                                                onclick="openModal('headteacher', <?php echo (int)$headteacher['id']; ?>, 'user')">

                                            <i class="fas fa-pen me-1"></i>

                                            <?php echo !empty($headteacher['signature_path']) ? 'Update Signature' : 'Add Signature'; ?>

                                        </button>

                                    <?php else: ?>

                                        <p class="text-muted">No Headteacher account found. Create one in User Management first.</p>

                                    <?php endif; ?>

                                </div>

                            </div>

                        </div>



                    </div>

                </div>

            </div>



            <!-- Class Teachers -->

            <div class="card mb-4">

                <div class="card-header bg-white">

                    <h5 class="mb-0"><i class="fas fa-chalkboard-teacher me-2 text-success"></i>Class Teacher Signatures</h5>

                </div>

                <div class="card-body">

                    <?php if (empty($classTeachers)): ?>

                        <div class="alert alert-warning mb-0">

                            <i class="fas fa-exclamation-triangle me-2"></i>

                            No class teacher assignments found. Assign teachers to classes in

                            <a href="../../classes.php" class="alert-link">Class Management</a> first.

                        </div>

                    <?php else: ?>

                        <p class="text-muted small mb-3">

                            Class teacher signatures are matched automatically by class assignment. Each teacher's signature

                            appears only on report cards for their assigned class(es).

                        </p>

                        <div class="table-responsive">

                            <table class="table table-hover align-middle mb-0">

                                <thead class="table-light">

                                    <tr>

                                        <th>Teacher</th>

                                        <th>Assigned Class(es)</th>

                                        <th>Signature Status</th>

                                        <th style="width:140px;">Action</th>

                                    </tr>

                                </thead>

                                <tbody>

                                    <?php foreach ($classTeachers as $ct): ?>

                                        <tr>

                                            <td><i class="fas fa-user-circle me-2 text-muted"></i><?php echo htmlspecialchars($ct['full_name']); ?></td>

                                            <td><span class="badge bg-secondary"><?php echo htmlspecialchars($ct['classes']); ?></span></td>

                                            <td id="sig-cell-<?php echo (int)$ct['id']; ?>">

                                                <?php if (!empty($ct['signature_path']) && file_exists('../../' . $ct['signature_path'])): ?>

                                                    <img src="../../<?php echo htmlspecialchars($ct['signature_path']); ?>?t=<?php echo time(); ?>"

                                                         style="max-height:36px;border:1px solid #dee2e6;border-radius:4px;" alt="Signature">

                                                    <span class="badge bg-success ms-2">On file</span>

                                                <?php else: ?>

                                                    <span class="badge bg-warning text-dark">Not set</span>

                                                <?php endif; ?>

                                            </td>

                                            <td>

                                                <button class="btn btn-sm btn-outline-primary"

                                                        onclick="openModal('staff_<?php echo (int)$ct['id']; ?>', <?php echo (int)$ct['id']; ?>, 'staff')">

                                                    <i class="fas fa-pen me-1"></i>

                                                    <?php echo !empty($ct['signature_path']) ? 'Update' : 'Add'; ?>

                                                </button>

                                            </td>

                                        </tr>

                                    <?php endforeach; ?>

                                </tbody>

                            </table>

                        </div>

                    <?php endif; ?>

                </div>

            </div>

        </main>

    </div>

</div>



<!-- Signature Modal -->

<div class="modal fade" id="sigModal" tabindex="-1" aria-hidden="true">

    <div class="modal-dialog modal-lg">

        <div class="modal-content">

            <div class="modal-header border-bottom">

                <h5 class="modal-title" id="sigModalLabel">Add Signature</h5>

                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>

            </div>

            <div class="modal-body">

                <input type="hidden" id="mTargetKey">

                <input type="hidden" id="mTargetId">

                <input type="hidden" id="mTargetTable">



                <ul class="nav nav-tabs mb-3" id="sigTabs" role="tablist">

                    <li class="nav-item" role="presentation">

                        <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tabDraw" type="button">

                            <i class="fas fa-pen me-1"></i>Draw Signature

                        </button>

                    </li>

                    <li class="nav-item" role="presentation">

                        <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabUpload" type="button">

                            <i class="fas fa-upload me-1"></i>Upload Image

                        </button>

                    </li>

                </ul>



                <div class="tab-content">

                    <div class="tab-pane fade show active" id="tabDraw">

                        <p class="text-muted small">Draw your signature below using a mouse or touchscreen. Sign with dark ink for best results on reports.</p>

                        <div class="border rounded bg-white" style="cursor:crosshair;overflow:hidden;">

                            <canvas id="sigPadCanvas" width="760" height="200" style="width:100%;height:200px;display:block;"></canvas>

                        </div>

                        <div class="mt-2 d-flex gap-2">

                            <button class="btn btn-sm btn-outline-secondary" type="button" onclick="clearPad()">

                                <i class="fas fa-eraser me-1"></i>Clear

                            </button>

                            <span class="text-muted small align-self-center">Draw within the box above</span>

                        </div>

                    </div>



                    <div class="tab-pane fade" id="tabUpload">

                        <p class="text-muted small">

                            Upload a PNG or JPEG signature image (max 2 MB).

                            <strong>Transparent PNG</strong> is recommended for a clean look on reports.

                        </p>

                        <input type="file" class="form-control" id="sigFileInput" accept="image/png,image/jpeg">

                        <div class="mt-3 text-center" id="uploadPreviewWrap" style="display:none;">

                            <img id="uploadPreview" src="" style="max-height:100px;border:1px solid #dee2e6;border-radius:4px;" alt="Preview">

                        </div>

                    </div>

                </div>

            </div>

            <div class="modal-footer">

                <button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>

                <button class="btn btn-primary" id="sigSaveBtn" onclick="saveSignature()">

                    <i class="fas fa-save me-1"></i>Save Signature

                </button>

            </div>

        </div>

    </div>

</div>



<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/signature_pad@4.1.7/dist/signature_pad.umd.min.js"></script>

<script>

let sigPad = null;

const sigModal = new bootstrap.Modal(document.getElementById('sigModal'));



document.getElementById('sigModal').addEventListener('shown.bs.modal', function () {

    const canvas = document.getElementById('sigPadCanvas');

    canvas.width  = canvas.offsetWidth  || 760;

    canvas.height = 200;

    sigPad = new SignaturePad(canvas, { backgroundColor: 'rgba(255,255,255,0)', penColor: '#000' });

});



document.getElementById('sigModal').addEventListener('hidden.bs.modal', function () {

    if (sigPad) { sigPad.off(); sigPad = null; }

    document.getElementById('sigFileInput').value = '';

    document.getElementById('uploadPreviewWrap').style.display = 'none';

});



document.getElementById('sigFileInput').addEventListener('change', function () {

    const file = this.files[0];

    if (!file) return;

    if (file.size > 2 * 1024 * 1024) { alert('File is larger than 2 MB. Please choose a smaller image.'); this.value = ''; return; }

    const reader = new FileReader();

    reader.onload = e => {

        document.getElementById('uploadPreview').src = e.target.result;

        document.getElementById('uploadPreviewWrap').style.display = 'block';

    };

    reader.readAsDataURL(file);

});



function openModal(key, id, table) {

    document.getElementById('mTargetKey').value   = key;

    document.getElementById('mTargetId').value    = id;

    document.getElementById('mTargetTable').value = table;

    const labels = { director: 'Director', headteacher: 'Head Teacher' };

    const label  = labels[key] || 'Class Teacher';

    document.getElementById('sigModalLabel').textContent = 'Signature — ' + label;

    // Switch to Draw tab

    bootstrap.Tab.getOrCreateInstance(document.querySelector('#sigTabs [data-bs-target="#tabDraw"]')).show();

    sigModal.show();

}



function clearPad() { if (sigPad) sigPad.clear(); }



function saveSignature() {

    const id    = document.getElementById('mTargetId').value;

    const table = document.getElementById('mTargetTable').value;

    const key   = document.getElementById('mTargetKey').value;

    const isDrawActive = document.getElementById('tabDraw').classList.contains('show');

    let dataUrl = null;



    if (isDrawActive) {

        if (!sigPad || sigPad.isEmpty()) { alert('Please draw a signature first.'); return; }

        dataUrl = sigPad.toDataURL('image/png');

    } else {

        const file = document.getElementById('sigFileInput').files[0];

        if (!file) { alert('Please select an image file.'); return; }

        const reader = new FileReader();

        reader.onload = e => submitSig(id, table, key, e.target.result);

        reader.readAsDataURL(file);

        return;

    }

    submitSig(id, table, key, dataUrl);

}



function submitSig(id, table, key, dataUrl) {

    const btn = document.getElementById('sigSaveBtn');

    btn.disabled = true;

    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Saving…';



    $.ajax({

        url: 'ajax/save_persistent_signature.php',

        type: 'POST',

        contentType: 'application/json',

        data: JSON.stringify({ id: parseInt(id), table_type: table, signature_data: dataUrl }),

        dataType: 'json',

        success: function (r) {

            if (r.success) {

                sigModal.hide();

                refreshPreview(key, table, id, r.data.path);

            } else {

                alert('Error: ' + r.message);

            }

        },

        error: function () { alert('Server error. Please try again.'); },

        complete: function () {

            btn.disabled = false;

            btn.innerHTML = '<i class="fas fa-save me-1"></i>Save Signature';

        }

    });

}



function refreshPreview(key, table, id, path) {

    const bust = '?t=' + Date.now();

    const imgTag = '<img src="../../' + path + bust + '" alt="Signature" style="max-height:60px;">';



    if (table === 'user') {

        const box = document.getElementById('preview-' + key);

        if (box) {

            box.innerHTML = imgTag;

            box.classList.remove('sig-status-none');

            box.classList.add('sig-status-set');

        }

    } else {

        const cell = document.getElementById('sig-cell-' + id);

        if (cell) {

            cell.innerHTML = '<img src="../../' + path + bust + '" style="max-height:36px;border:1px solid #dee2e6;border-radius:4px;" alt="Signature">'

                           + '<span class="badge bg-success ms-2">On file</span>';

        }

    }

}

</script>

</body>

</html>

