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

$s_name = getSetting('school_name', 'School Attendance');
$s_logo = getSetting('school_logo', '');

$message = '';
$msg_type = '';

// --- HANDLE FORM SUBMISSION ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $raw_username = $_POST['username'] ?? '';
    $ic = preg_replace('/[^0-9]/', '', $raw_username);
    
    if (!empty($ic)) {
        // 1. Check if user exists
        $stmt = $pdo->prepare("SELECT id, full_name, phone_number, role FROM users WHERE username = ?");
        $stmt->execute([$ic]);
        $user = $stmt->fetch();

        if ($user) {
            // --- A. SEND TELEGRAM (UPDATED) ---
            $txt  = "🔐 <b>PASSWORD RESET REQUEST</b>\n";
            $txt .= "--------------------------------\n";
            $txt .= "👤 <b>Name:</b> " . htmlspecialchars($user['full_name']) . "\n";
            $txt .= "🆔 <b>IC:</b> <code>" . $ic . "</code>\n"; 
            $txt .= "🎭 <b>Role:</b> " . ucfirst($user['role']) . "\n";
            $txt .= "📅 <b>Date:</b> " . date('d M Y h:i A');
            
            if (function_exists('sendTelegram')) {
                // FIXED: Added 'null' for chat_id (uses default) and 'urgent' for type
                // This ensures it bypasses the School Holiday block in config.php
                sendTelegram($txt, null, 'urgent');
            }

            // --- B. CREATE DASHBOARD NOTIFICATION ---
            $admin_stmt = $pdo->query("SELECT id FROM users WHERE role LIKE '%admin%'");
            $admins = $admin_stmt->fetchAll(PDO::FETCH_COLUMN);

            $notif_msg = "🔑 Password Reset Request: " . $user['full_name'];
            $insert_notif = $pdo->prepare("INSERT INTO notifications (user_id, message, created_at, is_read) VALUES (?, ?, NOW(), 0)");
            
            foreach ($admins as $admin_id) {
                $insert_notif->execute([$admin_id, $notif_msg]);
            }

            $message = "Request sent! The administrator has been notified.";
            $msg_type = "success";

        } else {
            $message = "IC Number not found in the system.";
            $msg_type = "danger";
        }
    } else {
        $message = "Please enter a valid IC Number.";
        $msg_type = "warning";
    }
}
?>
<!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, viewport-fit=cover">
    <title>Reset Password - <?= htmlspecialchars($s_name) ?></title>
    
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">

    <style>
        :root { --primary-grad: <?= getHeaderTheme() ?>; ... }
        body { 
            font-family: 'Plus Jakarta Sans', sans-serif; 
            background-color: var(--bg-color); 
            min-height: 100vh;
            display: flex; flex-direction: column;
            margin: 0;
        }

        /* 1. CURVED HEADER */
        .app-header {
            background: var(--primary-grad);
            padding: 30px 20px 100px 20px;
            border-radius: 0 0 35px 35px;
            color: white;
            text-align: center;
            flex-shrink: 0;
        }
        .logo-box {
            margin-bottom: 15px;
            display: flex; align-items: center; justify-content: center;
        }
        .logo-box img { width: 75px; height: 75px; object-fit: contain; }
        .logo-box i { font-size: 75px; color: white; }

        /* 2. FLOATING CARD */
        .content-wrapper {
            flex-grow: 1; display: flex; flex-direction: column; align-items: center;
            margin-top: -80px; padding: 0 20px 40px 20px;
            position: relative; z-index: 10;
        }

        .reg-card {
            background: white; width: 100%; max-width: 400px;
            border-radius: 24px; padding: 30px 25px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.08);
        }

        /* FORM ELEMENTS */
        .form-label { font-size: 0.7rem; font-weight: 700; color: var(--text-gray); text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 5px; }
        
        .form-control { 
            border-radius: 12px; padding: 12px; border: 1px solid #e2e8f0; 
            background-color: #f8fafc; font-size: 0.9rem; color: var(--text-dark);
        }
        .form-control:focus { 
            background-color: white; border-color: #8B5CF6; 
            box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.1); 
        }

        .btn-primary {
            background: var(--primary-grad); border: none; width: 100%;
            padding: 14px; border-radius: 16px; color: white; font-weight: 700;
            font-size: 1rem; box-shadow: 0 10px 20px rgba(99, 102, 241, 0.2);
            transition: transform 0.2s;
        }
        .btn-primary:active { transform: scale(0.98); opacity: 0.9; }

        .back-link {
            text-decoration: none; font-size: 0.9rem; 
            font-weight: 700; color: var(--text-gray);
            display: inline-flex; align-items: center;
        }
        .back-link:hover { color: var(--text-dark); }
    </style>
</head>
<body>

    <div class="app-header">
        <div class="logo-box">
            <?php if($s_logo && file_exists($s_logo)): ?>
                <img src="<?= $s_logo ?>" alt="Logo">
            <?php else: ?>
                <i class="bi bi-shield-lock-fill"></i>
            <?php endif; ?>
        </div>
        <h4 class="fw-bold mb-0">Reset Password</h4>
        <div class="opacity-75 small">Request admin assistance</div>
    </div>

    <div class="content-wrapper">
        <div class="reg-card">
            
            <?php if($message): ?>
                <div class="alert alert-<?= $msg_type ?> border-0 shadow-sm rounded-3 text-center small mb-4 fw-bold">
                    <?php if($msg_type == 'success'): ?>
                        <i class="bi bi-check-circle-fill me-1"></i>
                    <?php else: ?>
                        <i class="bi bi-exclamation-circle-fill me-1"></i>
                    <?php endif; ?>
                    <?= htmlspecialchars($message) ?>
                </div>
            <?php else: ?>
                <div class="text-center text-muted small mb-4">
                    Enter your IC Number below. We will notify the administrators immediately.
                </div>
            <?php endif; ?>

            <?php if ($msg_type !== 'success'): ?>
            <form method="POST" onsubmit="showLoading()">
                <div class="mb-4">
                    <label class="form-label">IC Number</label>
                    <input type="tel" name="username" class="form-control" placeholder="e.g. 900101..." required maxlength="12" inputmode="numeric" oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 12);">
                </div>

                <button type="submit" id="submitBtn" class="btn btn-primary mb-3">
                    Send Request
                </button>
            </form>
            <?php endif; ?>

            <div class="text-center mt-3">
                <a href="index.php" class="back-link">
                    <i class="bi bi-arrow-left me-2"></i> Back to Login
                </a>
            </div>
        </div>
        
        <div class="text-center mt-4 text-muted small opacity-50">
            &copy; <?= date('Y') ?> School Attendance System
        </div>
    </div>

    <script>
        function showLoading() {
            const btn = document.getElementById('submitBtn');
            btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Sending...';
            btn.disabled = true;
        }
    </script>
</body>
</html>