<?php
// Filename: public_parent.php
require 'config.php';

// Start Session
if (session_status() === PHP_SESSION_NONE) session_start();

// --- 1. FETCH SETTINGS & CHECK STATUS ---
$portal_enabled = getSetting('parent_portal_enabled', '1');
$s_name = getSetting('school_name', 'SAS');
$s_logo = getSetting('school_logo', '');
$s_address = getSetting('school_address', 'School General Office');
$s_phone = getSetting('school_phone', '');
$s_info = getSetting('school_info', ''); 

if ($portal_enabled !== '1') {
    die("<!DOCTYPE html><html lang='en'><head><meta charset='UTF-8'><meta name='viewport' content='width=device-width,initial-scale=1.0'><title>Closed</title><link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'></head><body class='bg-light d-flex align-items-center justify-content-center vh-100'><div class='text-center p-5 bg-white shadow rounded-4'><h4>Portal Closed</h4><p class='text-muted small'>Currently disabled.</p><a href='index.php' class='btn btn-primary rounded-pill mt-2'>Staff Login</a></div></body></html>");
}

// --- 2. INIT VARIABLES ---
$student = null;
$attendance_stats = null;
$discipline_stats = null;
$warning_status = null; 
$msg = ''; 
$msg_type = '';
// Only exclude specific holiday types from calculation. 
// 'school_event' and 'cuti_ganti' are treated as School Days (included in stats).
$holiday_filter = " AND NOT EXISTS (
    SELECT 1 FROM school_holidays h 
    WHERE student_attendance.date BETWEEN h.start_date AND h.end_date 
    AND h.type IN ('national', 'special', 'cuti_peristiwa', 'term')
) ";

// --- 3. HANDLE ACTIONS ---

// A. RESET
if (isset($_GET['reset'])) {
    unset($_SESSION['parent_view_ic']);
    header("Location: public_parent.php");
    exit;
}

// B. UPDATE CONTACT
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_contact') {
    $ic = $_SESSION['parent_view_ic'] ?? '';
    $new_phone = trim($_POST['parent_phone']);
    $new_chat_id = trim($_POST['parent_chat_id']);
    
    if ($ic) {
        try {
            $upd = $pdo->prepare("UPDATE students SET parent_phone = ?, parent_chat_id = ? WHERE ic_number = ?");
            if ($upd->execute([$new_phone, $new_chat_id, $ic])) {
                $msg = "Contact details updated successfully.";
                $msg_type = "success";
            } else {
                $msg = "Update failed."; $msg_type = "danger";
            }
        } catch (Exception $e) { $msg = "Error: " . $e->getMessage(); $msg_type = "danger"; }
    }
}

// C. LOGIN SEARCH (UPDATED CAPTCHA CHECK)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'search') {
    $user_ans = trim($_POST['captcha']);
    $ic = trim($_POST['ic_number']);

    // 1. Validate Captcha
    if (!isset($_SESSION['captcha_code']) || $user_ans != $_SESSION['captcha_code']) {
        $msg = "Incorrect security code."; 
        $msg_type = "danger";
        // We allow standard reload to generate new code via image request
    } 
    // 2. Validate Input
    elseif (empty($ic)) {
        $msg = "Please enter an IC Number."; 
        $msg_type = "warning";
    } 
    // 3. Success Path
    else {
        $chk = $pdo->prepare("SELECT id FROM students WHERE ic_number = ?");
        $chk->execute([$ic]);
        if ($chk->fetch()) {
            $_SESSION['parent_view_ic'] = $ic;
            unset($_SESSION['captcha_code']); // Clear on success
        } else {
            $msg = "Student not found."; 
            $msg_type = "danger";
        }
    }
}

// --- 4. DATA FETCHING ---
if (isset($_SESSION['parent_view_ic'])) {
    $ic = $_SESSION['parent_view_ic'];
    $stmt = $pdo->prepare("SELECT s.*, c.class_name, c.form_level, u.full_name as teacher_name, u.phone_number as teacher_phone FROM students s LEFT JOIN classes c ON s.class_id = c.id LEFT JOIN users u ON c.class_teacher_id = u.id WHERE s.ic_number = ?");
    $stmt->execute([$ic]);
    $student = $stmt->fetch();

    if ($student) {
        // Stats
        $att_q = $pdo->prepare("SELECT status, count(*) as count FROM student_attendance WHERE student_id = ? $holiday_filter GROUP BY status");
        $att_q->execute([$student['id']]);
        $att_data = $att_q->fetchAll(PDO::FETCH_KEY_PAIR);
        $absent = $att_data['absent'] ?? 0;
        $present = $att_data['present'] ?? 0;
        $total_days = $absent + $present;
        $attendance_rate = ($total_days > 0) ? round(($present / $total_days) * 100) : 100;
        
        $attendance_stats = [
            'rate' => $attendance_rate,
            'absent' => $absent,
            'history' => $pdo->prepare("SELECT date, reason FROM student_attendance WHERE student_id = ? AND status='absent' $holiday_filter ORDER BY date DESC LIMIT 5")
        ];
        $attendance_stats['history']->execute([$student['id']]);
        
        $disc_q = $pdo->prepare("SELECT * FROM student_discipline WHERE student_id = ? ORDER BY reported_date DESC");
        $disc_q->execute([$student['id']]);
        $discipline_stats = $disc_q->fetchAll();

        // SSDM Warning
        $hist_stmt = $pdo->prepare("SELECT status FROM student_attendance WHERE student_id = ? $holiday_filter ORDER BY date DESC");
        $hist_stmt->execute([$student['id']]);
        $full_history = $hist_stmt->fetchAll(PDO::FETCH_COLUMN);

        $streak = 0; $streak_active = true;
        foreach ($full_history as $status) { if ($status === 'absent') { if ($streak_active) $streak++; } else { $streak_active = false; } }

        if ($streak >= 7) $warning_status = ['level' => 'danger', 'title' => 'Critical Warning (7 Days)', 'msg' => 'Student absent for 7 consecutive days.'];
        elseif ($streak >= 3) $warning_status = ['level' => 'warning', 'title' => 'Warning (3 Days)', 'msg' => 'Student absent for 3 consecutive days.'];
        elseif ($absent >= 60) $warning_status = ['level' => 'danger', 'title' => 'Critical (>60 Days)', 'msg' => 'Total absences exceeded 60 days.'];
    } else {
        unset($_SESSION['parent_view_ic']);
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Parent Portal</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Poppins', sans-serif; background-color: #f0f2f5; padding-bottom: 80px; }
        
        .hero-header { 
            background: linear-gradient(135deg, #0d6efd 0%, #0099ff 100%); 
            color: white; border-radius: 0 0 30px 30px; padding: 40px 20px 60px 20px; text-align: center; margin-bottom: -40px; 
            box-shadow: 0 4px 20px rgba(13, 110, 253, 0.2);
        }
        .school-logo { width: 90px; height: 90px; object-fit: contain; margin-bottom: 10px; filter: drop-shadow(0 4px 6px rgba(0,0,0,0.2)); }
        
        .main-card { background: white; border-radius: 20px; border: 0; box-shadow: 0 10px 30px rgba(0,0,0,0.08); overflow: hidden; margin-bottom: 20px; }
        .profile-icon { width: 70px; height: 70px; border-radius: 50%; background: #e7f1ff; color: #0d6efd; display: flex; align-items: center; justify-content: center; font-size: 2rem; margin: 0 auto 15px auto; border: 4px solid white; box-shadow: 0 4px 10px rgba(0,0,0,0.1); }
        .stat-badge { background: #f8f9fa; border-radius: 12px; padding: 10px; text-align: center; height: 100%; border: 1px solid #eee; }
        .stat-val { font-size: 1.2rem; font-weight: 800; display: block; }
        .stat-lbl { font-size: 0.7rem; text-transform: uppercase; color: #6c757d; font-weight: 600; }
        .warning-card { background: #fff3cd; border-left: 5px solid #ffc107; color: #664d03; }
        .warning-card.danger { background: #f8d7da; border-left: 5px solid #dc3545; color: #842029; }
        .contact-card { background: #e7f1ff; border-radius: 15px; padding: 15px; border: 1px solid #cce5ff; color: #004085; }
        
        /* Captcha Image Style */
        .captcha-img { cursor: pointer; border-radius: 8px; border: 1px solid #dee2e6; height: 40px; }
    </style>
</head>
<body>

    <div class="hero-header">
        <?php if($s_logo && file_exists($s_logo)): ?>
            <img src="<?= $s_logo ?>" class="school-logo" alt="School Logo">
        <?php else: ?>
            <div class="mb-2"><i class="bi bi-person-hearts display-1 text-white opacity-50"></i></div>
        <?php endif; ?>
        <h2 class="fw-bold mb-0"><?= htmlspecialchars($s_name) ?></h2>
        <p class="opacity-75 small mb-0"><?= htmlspecialchars($s_address) ?></p>
        <div class="mt-2 badge bg-white bg-opacity-25 text-white fw-normal">Parent Portal</div>
    </div>

    <div class="container px-3">
        
        <?php if (!$student): ?>
            <div class="main-card p-4 mx-auto" style="max-width: 500px;">
                <?php if($msg): ?><div class="alert alert-<?= $msg_type ?> text-center small mb-4 rounded-3"><?= $msg ?></div><?php endif; ?>
                <form method="POST">
                    <input type="hidden" name="action" value="search">
                    <div class="mb-3 text-center">
                        <label class="form-label fw-bold text-secondary">Enter Student IC Number</label>
                        <input type="text" name="ic_number" class="form-control form-control-lg text-center fw-bold" placeholder="e.g. 090101015566" required inputmode="numeric">
                    </div>
                    
                    <div class="mb-4 text-center">
                        <label class="form-label small text-muted">Security Code (Tap to refresh)</label>
                        <div class="d-flex justify-content-center align-items-center gap-2">
                            <img src="captcha.php" onclick="this.src='captcha.php?'+Math.random()" class="captcha-img shadow-sm" title="Click to Refresh">
                            <input type="number" name="captcha" class="form-control text-center fw-bold" style="width: 100px; height: 40px;" required placeholder="Code">
                        </div>
                    </div>

                    <button class="btn btn-primary w-100 btn-lg rounded-pill fw-bold shadow-sm">Check Record</button>
                </form>
            </div>
            <div class="text-center mt-4 text-muted small"><a href="index.php" class="text-decoration-none text-muted"><i class="bi bi-shield-lock me-1"></i> Staff Login</a></div>

        <?php else: ?>
            
            <div class="main-card p-4 text-center position-relative mt-4">
                <a href="public_parent.php?reset=1" class="position-absolute top-0 end-0 m-3 text-muted"><i class="bi bi-x-circle fs-4"></i></a>
                <div class="profile-icon"><i class="bi bi-backpack"></i></div>
                <h4 class="fw-bold text-dark mb-0"><?= htmlspecialchars($student['full_name']) ?></h4>
                <div class="text-muted small mb-3"><?= htmlspecialchars($student['ic_number']) ?></div>
                
                <span class="badge bg-primary rounded-pill px-3 py-2 mb-3 text-wrap lh-base">
                    Form <?= $student['form_level'] ?> - <?= htmlspecialchars($student['class_name']) ?> 
                    &bull; <?= htmlspecialchars($student['teacher_name'] ?? 'No Teacher') ?>
                </span>

                <?php if($warning_status): ?>
                    <div class="alert warning-card <?= $warning_status['level']=='danger' ? 'danger' : '' ?> text-start mt-2 mb-3 shadow-sm border-0">
                        <div class="d-flex align-items-center"><i class="bi bi-exclamation-triangle-fill fs-3 me-3"></i><div><h6 class="fw-bold mb-1"><?= $warning_status['title'] ?></h6><div class="small" style="line-height:1.3;"><?= $warning_status['msg'] ?></div></div></div>
                    </div>
                <?php endif; ?>

                <div class="row g-2 mt-2">
                    <div class="col-4"><div class="stat-badge"><span class="stat-val text-success"><?= $attendance_stats['rate'] ?>%</span><span class="stat-lbl">Attd</span></div></div>
                    <div class="col-4"><div class="stat-badge"><span class="stat-val text-danger"><?= $attendance_stats['absent'] ?></span><span class="stat-lbl">Absent</span></div></div>
                    <div class="col-4"><div class="stat-badge"><span class="stat-val text-warning"><?= count($discipline_stats) ?></span><span class="stat-lbl">Cases</span></div></div>
                </div>
            </div>

            <?php if($msg): ?><div class="alert alert-<?= $msg_type ?> alert-dismissible fade show shadow-sm border-0 rounded-3 mb-3"><i class="bi bi-check-circle-fill me-2"></i> <?= $msg ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

            <div class="main-card">
                <div class="card-body p-3">
                    <h6 class="fw-bold text-danger mb-3"><i class="bi bi-telephone-plus-fill me-2"></i>Emergency Contact</h6>
                    <form method="POST" class="row g-2 align-items-center">
                        <input type="hidden" name="action" value="update_contact">
                        
                        <div class="col-12">
                            <label class="small text-muted fw-bold">Phone Number</label>
                            <input type="text" name="parent_phone" class="form-control bg-light" value="<?= htmlspecialchars($student['parent_phone']) ?>" placeholder="e.g. 0123456789">
                        </div>
                        
                        <div class="col-12">
                            <label class="small text-muted fw-bold">Telegram Chat ID <a href="https://t.me/userinfobot" target="_blank" class="text-decoration-none small ms-1">(Get ID)</a></label>
                            <input type="text" name="parent_chat_id" class="form-control bg-light" value="<?= htmlspecialchars($student['parent_chat_id'] ?? '') ?>" placeholder="12345678">
                        </div>

                        <div class="col-12 mt-3"><button class="btn btn-danger w-100 fw-bold">Save Details</button></div>
                    </form>
                    <div class="form-text small mt-2 text-center">Update this so teachers can reach you urgently.</div>
                </div>
            </div>

            <div class="main-card contact-card mb-3">
                <div class="card-body p-3">
                    <h6 class="fw-bold text-primary mb-3"><i class="bi bi-building-fill me-2"></i>Contact School</h6>
                    
                    <div class="d-flex align-items-center justify-content-between mb-3 pb-3 border-bottom border-primary border-opacity-25">
                        <div><div class="small fw-bold text-uppercase opacity-75">WhatsApp Teacher</div><div class="fw-bold">Click to Chat</div></div>
                        <?php if(!empty($student['teacher_phone'])): $wa = preg_replace('/[^0-9]/', '', $student['teacher_phone']); if(substr($wa,0,1)=='0')$wa='6'.$wa; ?>
                            <a href="https://wa.me/<?= $wa ?>" target="_blank" class="btn btn-success rounded-circle shadow-sm" style="width:40px; height:40px; display:flex; align-items:center; justify-content:center;"><i class="bi bi-whatsapp"></i></a>
                        <?php else: ?><button class="btn btn-light rounded-circle text-muted" disabled style="width:40px; height:40px;"><i class="bi bi-telephone-x"></i></button><?php endif; ?>
                    </div>

                    <div class="d-flex align-items-center justify-content-between">
                        <div>
                            <div class="small fw-bold text-uppercase opacity-75">School Office</div>
                            <div class="fw-bold text-truncate" style="max-width: 200px;"><?= htmlspecialchars($s_phone ?: 'No Phone') ?></div>
                        </div>
                        
                        <?php if($s_phone): $clean_phone = preg_replace('/[^0-9]/', '', $s_phone); ?>
                            <a href="tel:<?= $clean_phone ?>" class="btn btn-primary rounded-circle shadow-sm" style="width:40px; height:40px; display:flex; align-items:center; justify-content:center;"><i class="bi bi-telephone-fill"></i></a>
                        <?php else: ?>
                             <button class="btn btn-light text-muted rounded-circle" disabled style="width:40px; height:40px;"><i class="bi bi-telephone-x"></i></button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="main-card p-0">
                <div class="p-3 border-bottom bg-light fw-bold text-secondary"><i class="bi bi-calendar-event me-2"></i>Recent Absences (Holidays Excluded)</div>
                <?php 
                $rows = $attendance_stats['history']->fetchAll();
                if(empty($rows)): ?>
                    <div class="text-center py-4 text-muted small">No recent absences.</div>
                <?php else: ?>
                    <ul class="list-group list-group-flush">
                        <?php foreach($rows as $r): ?>
                            <li class="list-group-item d-flex justify-content-between align-items-center p-3">
                                <div><div class="fw-bold text-dark"><?= date('d M Y', strtotime($r['date'])) ?></div><small class="text-muted"><?= date('l', strtotime($r['date'])) ?></small></div>
                                <span class="badge bg-danger bg-opacity-10 text-danger"><?= htmlspecialchars($r['reason'] ?? 'Absent') ?></span>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>

        <?php endif; ?>
    </div>

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