<?php
include_once 'connect.php';
$error = '';
$success = '';
$emis_code = '';
$school_id = '';
$school_name = '';
$school_email_db = '';

// =====================
// GET EMIS_CODE FROM LOGIN
// =====================
if (isset($_GET['emis_code']) && !empty($_GET['emis_code'])) {
    $emis_code = trim($_GET['emis_code']);
    
    // Validate EMIS code format (11 digits)
    if (!preg_match('/^\d{11}$/', $emis_code)) {
        header("Location: login.php?forgot_error=" . urlencode("Invalid EMIS Code format."));
        exit();
    }
    
    $stmt = $conn->prepare(
        "SELECT id, school_name, school_email, status 
         FROM registrations 
         WHERE emis_code = ?"
    );
    $stmt->bind_param("s", $emis_code);
    $stmt->execute();
    $stmt->bind_result($school_id, $school_name, $school_email_db, $status);
    $stmt->fetch();
    $stmt->close();
    
    if (empty($school_id)) {
        header("Location: login.php?forgot_error=" . urlencode("EMIS Code not found. You cannot reset password."));
        exit();
    } elseif ($status != 1) {
        header("Location: login.php?forgot_error=" . urlencode("Account is inactive. You cannot reset password."));
        exit();
    }
} else {
    header("Location: login.php");
    exit();
}

// =====================
// PASSWORD VALIDATION FUNCTION
// =====================
function validate_password($password) {
    if (strlen($password) < 8) return "Password must be at least 8 characters long.";
    if (!preg_match('/[A-Z]/', $password)) return "Password must contain at least one uppercase letter.";
    if (!preg_match('/[a-z]/', $password)) return "Password must contain at least one lowercase letter.";
    if (!preg_match('/\d/', $password)) return "Password must contain at least one number.";
    return true;
}

// =====================
// HANDLE FORM SUBMIT
// =====================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $verification_email = trim($_POST['verification_email'] ?? '');
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $school_id = $_POST['school_id'] ?? '';
    
    // Email verification logic
    if (empty($verification_email)) {
        $error = "School email is required for verification.";
    } elseif (!empty($school_email_db) && $verification_email !== $school_email_db) {
        // If email exists in DB, entered email MUST match exactly
        $error = "Email does not match our records. Please enter the correct email.";
    } elseif (empty($new_password) || empty($confirm_password)) {
        $error = "Both password fields are required.";
    } elseif ($new_password !== $confirm_password) {
        $error = "Passwords do not match.";
    } else {
        // If no email on record AND user entered one, save it
        if (empty($school_email_db) && !empty($verification_email)) {
            $update_stmt = $conn->prepare("UPDATE registrations SET school_email = ? WHERE id = ?");
            $update_stmt->bind_param("si", $verification_email, $school_id);
            if (!$update_stmt->execute()) {
                $error = "Failed to update email. Please try again.";
                $update_stmt->close();
                $conn->close();
                exit();
            }
            $update_stmt->close();
            $school_email_db = $verification_email;
        }
        
        if (empty($error)) {
            // Server-side password complexity check
            $validation = validate_password($new_password);
            if ($validation !== true) {
                $error = $validation;
            } else {
                $password_hash = password_hash($new_password, PASSWORD_DEFAULT);
                
                // Update password and flag for admin approval, deactivate account temporarily
                $stmt = $conn->prepare(
                    "UPDATE registrations 
                     SET password = ?, 
                         forgot_password_request = 1,
						 forgot_password_new = ?, 
                         status = 0 
                     WHERE id = ?"
                );
                $stmt->bind_param("ssi", $password_hash, $new_password, $school_id);
                
                if ($stmt->execute()) {
                    // ---------------- EMAIL CONFIGURATION ----------------
                    $to_email   = 'mohsinbashirraja@dsisajk.net, wajidmuzaffar@dsisajk.net, amirhamzakhan@dsisajk.net, shirazahmad@dsisajk.net, kabirahmed@dsisajk.net';
                    $from_email = 'noreply@dsisajk.net';
                    $subject = 'Forgot Password Request – School Approval Required';
                    $email_body = "
A forgot password request has been submitted and requires administrator approval.

School Details:
------------------
School Name     : $school_name
EMIS Code       : $emis_code
Email           : $school_email_db
Account Status  : Deactivated (pending approval)
Request Type    : Forgot Password Reset

Please review and approve this request from the admin panel.

This is an automated message from the DSIS Registration System.
";
                    $headers = [];
                    $headers[] = "From: DSIS Registration System <$from_email>";
                    $headers[] = "Reply-To: $from_email";
                    $headers[] = "Return-Path: $from_email";
                    $headers[] = "MIME-Version: 1.0";
                    $headers[] = "Content-Type: text/plain; charset=UTF-8";
                    $headers[] = "X-Mailer: PHP/" . phpversion();
                    
                    if (!mail($to_email, $subject, $email_body, implode("\r\n", $headers))) {
                        error_log('Forgot-password admin notification email failed for school: ' . $emis_code);
                    }
                    
                    $success = "Password reset request sent to administrator for approval. Your account is now deactivated until approval is granted.";
                } else {
                    $error = "Something went wrong. Please try again.";
                }
                $stmt->close();
            }
        }
    }
}
$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Forgot Password - School</title>
<link rel="stylesheet" href="https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css">
<style>
:root {
--primary: #3498db; --primary-dark: #2980b9; --secondary: #2c3e50;
--success: #2ecc71; --danger: #e74c3c; --border-radius: 8px;
--box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}
* {margin:0;padding:0;box-sizing:border-box;font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;}
body {background: linear-gradient(135deg, rgba(52,152,219,.85), rgba(46,204,113,.85)), url('images/login_bg.jpg') center/cover no-repeat fixed; min-height:100vh; display:flex; justify-content:center; align-items:center; padding:20px;}
.login-container {width:100%; max-width:450px; background:#fff; border-radius:var(--border-radius); box-shadow:var(--box-shadow); overflow:hidden;}
.login-header {background:var(--secondary); color:#fff; padding:25px 30px; text-align:center;}
.login-header h1 {font-size:28px;margin-bottom:5px;}
.login-header p {font-size:16px; opacity:0.8;}
.login-body {padding:30px;}
.input-group {margin-bottom:20px;position:relative;}
.input-group label {display:block;margin-bottom:8px;font-weight:500;font-size:14px;color:var(--secondary);}
.input-group input {width:100%;padding:14px 45px 14px 15px;border:1px solid #ddd;border-radius:var(--border-radius);font-size:15px;}
.input-group input:focus {border-color: var(--primary); box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2); outline: none;}
.input-group i {position:absolute;right:15px;top:42px;font-size:20px;color:var(--gray);cursor:pointer;}
.btn {width:100%;padding:14px;border:none;border-radius:var(--border-radius);font-size:16px;cursor:pointer;background:var(--primary);color:#fff;}
.btn:hover {background:var(--primary-dark);}
.alert {padding:12px;border-radius:var(--border-radius);margin-bottom:15px;font-size:14px;}
.alert-error {background:#fdecea;color:var(--danger);border-left:4px solid var(--danger);}
.alert-success {background:#eafaf1;color:var(--success);border-left:4px solid var(--success);}
.back-login {margin-top:20px;text-align:center;}
.back-login a {color:var(--primary);text-decoration:none;font-size:14px;}
.back-login a:hover {text-decoration:underline;}
small {display:block; margin-top:4px; font-size:12px;}
</style>
</head>
<body>
<div class="login-container">
    <div class="login-header">
        <h1><i class='bx bxs-school'></i> School Portal</h1>
        <p>Forgot Password</p>
    </div>
    <div class="login-body">
        <?php if ($error): ?>
            <div class="alert alert-error"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>
        <?php if ($success): ?>
            <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
        <?php endif; ?>
        
        <form method="POST" autocomplete="off" onsubmit="return validateForm()">
            <div class="input-group">
                <label>EMIS Code</label>
                <input type="text" value="<?= htmlspecialchars($emis_code) ?>" readonly>
            </div>
            
            <div class="input-group">
                <label>School Email for Verification *</label>
                <input type="email" name="verification_email" id="verification_email" 
                       value="<?= htmlspecialchars($verification_email ?? '') ?>" 
                       required placeholder="Enter your email to verify">
                <?php if (!empty($school_email_db)): ?>
                    <small style="color:var(--primary);">
                        <i class='bx bx-info-circle'></i> Enter the email ending with: 
                        <strong><?= htmlspecialchars(substr($school_email_db, strpos($school_email_db, '@'))) ?></strong>
                    </small>
                <?php else: ?>
                    <small style="color:var(--warning);">
                        <i class='bx bx-info-circle'></i> No email on record. Enter one to register it.
                    </small>
                <?php endif; ?>
            </div>
            
            <input type="hidden" name="school_id" value="<?= htmlspecialchars($school_id) ?>">
            
            <div class="input-group">
                <label>New Password</label>
                <input type="password" name="new_password" id="new_password" required>
                <i class='bx bx-show' onclick="togglePassword('new_password', this)"></i>
                <small style="color:red;">Must contain: uppercase, lowercase, and a number</small>
            </div>
            
            <div class="input-group">
                <label>Confirm Password</label>
                <input type="password" name="confirm_password" id="confirm_password" required>
                <i class='bx bx-show' onclick="togglePassword('confirm_password', this)"></i>
            </div>
            
            <button type="submit" class="btn">Send Reset Request</button>
            
            <div class="back-login">
                <a href="login.php"><i class='bx bx-arrow-back'></i> Back to Login</a>
            </div>
        </form>
    </div>
</div>

<script>
function togglePassword(id, icon){
    const input = document.getElementById(id);
    if(input.type === "password"){ 
        input.type = "text"; 
        icon.classList.replace('bx-show','bx-hide'); 
    } else { 
        input.type = "password"; 
        icon.classList.replace('bx-hide','bx-show'); 
    }
}

function validateForm() {
    const email = document.getElementById('verification_email').value;
    const pass1 = document.getElementById('new_password').value;
    const pass2 = document.getElementById('confirm_password').value;
    
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        alert("Please enter a valid email address.");
        return false;
    }
    if (pass1.length < 8 || !/[A-Z]/.test(pass1) || !/[a-z]/.test(pass1) || !/\d/.test(pass1)) {
        alert("Password must be at least 8 characters with uppercase, lowercase, and a number.");
        return false;
    }
    if (pass1 !== pass2) {
        alert("Passwords do not match.");
        return false;
    }
    return true;
}
</script>
</body>
</html>