<?php

declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) {

    session_start();

}

if (!isset($_SESSION['user_id'])) {

    header('Location: index.php');

    exit;

}

require_once 'config.php';

requireModule('parent_portal');

$conn = getDBConnection();

if (!$conn instanceof mysqli) {

    http_response_code(500);

    exit('Database connection failed.');

}

// Load students with guardian info for auto-fill

$students = [];

$result = $conn->query(

    "SELECT id, first_name, last_name, student_id AS student_code, class,

            father_name, father_phone, mother_name, mother_phone

     FROM students

     ORDER BY first_name, last_name"

);

while ($result && $row = $result->fetch_assoc()) {

    $students[] = $row;

}

// Build a JS-safe lookup: student_db_id => {name, phone}

$studentGuardianData = [];

foreach ($students as $s) {

    $name  = trim((string)($s['father_name']  ?: $s['mother_name']  ?? ''));

    $phone = trim((string)($s['father_phone'] ?: $s['mother_phone'] ?? ''));

    $studentGuardianData[(int)$s['id']] = [

        'name'  => $name,

        'phone' => $phone,

    ];

}

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

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

    <title>Parent Accounts</title>

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

    <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">

</head>

<body>

<div class="wrapper">

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

        <?php echo buildSidebar(basename($_SERVER['PHP_SELF'])); ?>

        </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><?= htmlspecialchars((string)($_SESSION['full_name'] ?? 'Admin')) ?>

                    </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 d-flex justify-content-between align-items-center">

                <div>

                    <h2><i class="fas fa-users me-2"></i>Parent Accounts</h2>

                    <p>Create portal accounts for parents by selecting a student — guardian data auto-fills from the student profile.</p>

                </div>

                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#parentModal" onclick="openCreateModal()">

                    <i class="fas fa-plus me-1"></i>Link Parent Account

                </button>

            </div>

            <div class="card">

                <div class="card-body">

                    <div class="table-responsive">

                        <table class="table table-hover" id="parentTable">

                            <thead><tr><th>Name</th><th>Phone</th><th>Email</th><th>Children</th><th>Last Login</th><th>Status</th><th>Actions</th></tr></thead>

                            <tbody></tbody>

                        </table>

                    </div>

                </div>

            </div>

        </main>

    </div>

</div>



<!-- Create / Edit Modal -->

<div class="modal fade" id="parentModal" tabindex="-1">

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

        <div class="modal-content">

            <form id="parentForm">

                <div class="modal-header">

                    <h5 class="modal-title" id="parentModalTitle">Link Parent Account</h5>

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

                </div>

                <div class="modal-body">

                    <input type="hidden" name="id" id="parentId" value="0">

                    <div class="row g-3">

                        <!-- Student selector — shown only for new accounts -->

                        <div class="col-md-12" id="studentSelectWrap">

                            <label class="form-label fw-semibold">Select Student <span class="text-danger">*</span></label>

                            <select name="student_id" id="studentSelect" class="form-select">

                                <option value="">— Choose a student —</option>

                                <?php foreach ($students as $s): ?>

                                    <option value="<?= (int)$s['id'] ?>">

                                        <?= htmlspecialchars(trim($s['first_name'] . ' ' . $s['last_name'])) ?>

                                        — <?= htmlspecialchars((string)$s['student_code']) ?>

                                        (<?= htmlspecialchars((string)$s['class']) ?>)

                                    </option>

                                <?php endforeach; ?>

                            </select>

                            <div class="form-text">Guardian data will auto-fill from the student's profile.</div>

                        </div>

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

                            <label class="form-label">Guardian Full Name <span class="text-danger">*</span></label>

                            <input type="text" name="full_name" id="parentFullName" class="form-control" required>

                        </div>

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

                            <label class="form-label">Phone (Portal Login) <span class="text-danger">*</span></label>

                            <input type="tel" name="phone" id="parentPhone" class="form-control" required>

                        </div>

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

                            <label class="form-label">Email</label>

                            <input type="email" name="email" id="parentEmail" class="form-control">

                        </div>

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

                            <label class="form-label" id="passwordLabel">Password <span class="text-danger">*</span></label>

                            <input type="text" name="password" id="parentPassword" class="form-control">

                            <div class="form-text" id="passwordHint">Leave blank to keep existing password when editing.</div>

                        </div>

                    </div>

                </div>

                <div class="modal-footer">

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

                    <button type="submit" class="btn btn-primary">Save Parent Account</button>

                </div>

            </form>

        </div>

    </div>

</div>



<!-- Send Notification Modal -->

<div class="modal fade" id="notificationModal" tabindex="-1">

    <div class="modal-dialog">

        <div class="modal-content">

            <form id="notificationForm">

                <div class="modal-header">

                    <h5 class="modal-title">Send Notification</h5>

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

                </div>

                <div class="modal-body">

                    <input type="hidden" name="target_type" value="one">

                    <input type="hidden" name="parent_id" id="notifyParentId" value="0">

                    <div class="mb-3">

                        <label class="form-label">Title</label>

                        <input type="text" name="title" class="form-control" required>

                    </div>

                    <div class="mb-3">

                        <label class="form-label">Message</label>

                        <textarea name="message" class="form-control" rows="4" required></textarea>

                    </div>

                    <div class="form-check">

                        <input class="form-check-input" type="checkbox" value="1" id="alsoSms" name="also_sms">

                        <label class="form-check-label" for="alsoSms">Also send SMS</label>

                    </div>

                </div>

                <div class="modal-footer">

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

                    <button type="submit" class="btn btn-primary">Send</button>

                </div>

            </form>

        </div>

    </div>

</div>



<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>

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

<script src="js/main.js"></script>

<script>

// Guardian data keyed by student DB id

const STUDENT_GUARDIAN = <?= json_encode($studentGuardianData, JSON_UNESCAPED_UNICODE) ?>;



// Cache parent rows for edit

const parentCache = {};



function esc(v) {

    return String(v ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c]));

}



// ── Student selector auto-fill ──────────────────────────────────────────

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

    const sid = parseInt(this.value, 10);

    const guardian = sid ? STUDENT_GUARDIAN[sid] : null;

    if (guardian) {

        document.getElementById('parentFullName').value = guardian.name || '';

        document.getElementById('parentPhone').value    = guardian.phone || '';

    }

});



// ── Open modal for NEW account ──────────────────────────────────────────

function openCreateModal() {

    const form = document.getElementById('parentForm');

    form.reset();

    document.getElementById('parentId').value = '0';

    document.getElementById('parentModalTitle').textContent = 'Link Parent Account';

    document.getElementById('studentSelectWrap').style.display = '';

    document.getElementById('passwordLabel').innerHTML = 'Password <span class="text-danger">*</span>';

    document.getElementById('passwordHint').textContent = 'Required for new accounts.';

    document.getElementById('parentPassword').required = true;

}



// ── Open modal for EDIT ─────────────────────────────────────────────────

function editParent(parentId) {

    const p = parentCache[parentId];

    if (!p) return;

    const form = document.getElementById('parentForm');

    form.reset();

    document.getElementById('parentId').value        = p.id;

    document.getElementById('parentFullName').value  = p.full_name || '';

    document.getElementById('parentPhone').value     = p.phone || '';

    document.getElementById('parentEmail').value     = p.email || '';

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

    document.getElementById('parentModalTitle').textContent = 'Edit Parent Account';

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

    document.getElementById('passwordLabel').innerHTML = 'New Password';

    document.getElementById('passwordHint').textContent = 'Leave blank to keep existing password.';

    document.getElementById('parentPassword').required = false;

    bootstrap.Modal.getOrCreateInstance(document.getElementById('parentModal')).show();

}



// ── Load parent list ────────────────────────────────────────────────────

async function loadParents() {

    const response = await fetch('ajax/get_parent_accounts.php', { method: 'POST' });

    const data = await response.json();

    (data || []).forEach(p => { parentCache[p.id] = p; });

    document.querySelector('#parentTable tbody').innerHTML = (data || []).map(p => `

        <tr>

            <td>${esc(p.full_name)}</td>

            <td>${esc(p.phone)}</td>

            <td>${esc(p.email || '')}</td>

            <td>${esc(p.children || '—')}</td>

            <td>${esc(p.last_login || 'Never')}</td>

            <td><span class="badge ${parseInt(p.is_active, 10) === 1 ? 'badge-success' : 'badge-warning'}">${parseInt(p.is_active, 10) === 1 ? 'Active' : 'Inactive'}</span></td>

            <td>

                <div class="action-buttons">

                    <button class="btn btn-sm btn-outline-primary" onclick="editParent(${p.id})">Edit</button>

                    <button class="btn btn-sm btn-outline-secondary" onclick="toggleStatus(${p.id})">${parseInt(p.is_active, 10) === 1 ? 'Deactivate' : 'Activate'}</button>

                    <button class="btn btn-sm btn-outline-info" onclick="openNotify(${p.id})">Notify</button>

                </div>

            </td>

        </tr>

    `).join('') || '<tr><td colspan="7" class="portal-muted text-center">No parent accounts found.</td></tr>';

}



// ── Toggle status ───────────────────────────────────────────────────────

async function toggleStatus(parentId) {

    const response = await fetch('ajax/save_parent_account.php', {

        method: 'POST',

        body: new URLSearchParams({ id: parentId, toggle_status: 1 })

    });

    const data = await response.json();

    if (data.success) loadParents();

    else alert(data.message || 'Failed');

}



// ── Send notification ───────────────────────────────────────────────────

function openNotify(parentId) {

    document.getElementById('notifyParentId').value = parentId;

    bootstrap.Modal.getOrCreateInstance(document.getElementById('notificationModal')).show();

}



// ── Form: save parent ───────────────────────────────────────────────────

document.getElementById('parentForm').addEventListener('submit', async function (event) {

    event.preventDefault();

    const formData = new FormData(this);

    const isNew = parseInt(formData.get('id') || '0', 10) === 0;

    // Require student for new accounts

    if (isNew && !formData.get('student_id')) {

        alert('Please select a student first.');

        return;

    }

    const response = await fetch('ajax/save_parent_account.php', {

        method: 'POST',

        body: new URLSearchParams(formData)

    });

    const data = await response.json();

    alert(data.message || 'Done');

    if (data.success) {

        bootstrap.Modal.getOrCreateInstance(document.getElementById('parentModal')).hide();

        this.reset();

        loadParents();

    }

});



// ── Form: send notification ─────────────────────────────────────────────

document.getElementById('notificationForm').addEventListener('submit', async function (event) {

    event.preventDefault();

    const response = await fetch('ajax/send_parent_notification.php', {

        method: 'POST',

        body: new URLSearchParams(new FormData(this))

    });

    const data = await response.json();

    alert(data.message || 'Done');

    if (data.success) {

        bootstrap.Modal.getOrCreateInstance(document.getElementById('notificationModal')).hide();

        this.reset();

    }

});



loadParents();

</script>

</body>

</html>

