<?php
declare(strict_types=1);
session_start();
require_once '../config.php';

$conn = getDBConnection();
$step = 1;
$phone = preg_replace('/\D+/', '', (string) ($_POST['phone'] ?? $_GET['phone'] ?? ''));
$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'request_otp') {
    if (!$conn instanceof mysqli || $phone === '') {
        $error = 'Enter a valid phone number.';
    } else {
        $otp = str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
        $stmt = $conn->prepare(
            "UPDATE parent_accounts
             SET otp_code = ?, otp_expires = DATE_ADD(NOW(), INTERVAL 15 MINUTE)
             WHERE phone = ? AND is_active = 1"
        );
        $stmt->bind_param('ss', $otp, $phone);
        $stmt->execute();
        $updated = $stmt->affected_rows > 0;
        $stmt->close();

        if ($updated) {
            sendSMS($phone, "EduTrack: Your password reset code is {$otp}. Valid for 15 minutes.");
            $step = 2;
            $success = 'OTP sent to the phone number on file.';
        } else {
            $error = 'No active parent account found for that phone number.';
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'reset_password') {
    $step = 2;
    $otpCode = trim((string) ($_POST['otp_code'] ?? ''));
    $newPassword = (string) ($_POST['new_password'] ?? '');
    $confirmPassword = (string) ($_POST['confirm_password'] ?? '');

    if ($newPassword === '' || $newPassword !== $confirmPassword) {
        $error = 'Passwords do not match.';
    } elseif (!$conn instanceof mysqli) {
        $error = 'Database connection failed.';
    } else {
        $stmt = $conn->prepare(
            "SELECT id
             FROM parent_accounts
             WHERE phone = ? AND otp_code = ? AND otp_expires > NOW()
             LIMIT 1"
        );
        $stmt->bind_param('ss', $phone, $otpCode);
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if (!$row) {
            $error = 'Invalid or expired OTP code.';
        } else {
            $hash = password_hash($newPassword, PASSWORD_BCRYPT);
            $update = $conn->prepare(
                "UPDATE parent_accounts
                 SET password_hash = ?, otp_code = NULL, otp_expires = NULL
                 WHERE id = ?"
            );
            $update->bind_param('si', $hash, $row['id']);
            $update->execute();
            $update->close();

            header('Location: login.php?success=' . urlencode('Password reset successful. Sign in now.'));
            exit;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Forgot Password</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="assets/css/portal.css">
</head>
<body>
    <div class="portal-auth-wrap">
        <div class="portal-auth-card">
            <div class="portal-auth-logo"><i class="fas fa-key"></i></div>
            <h1 class="h4 text-center mb-2">Reset Parent Password</h1>
            <p class="portal-subtitle text-center mb-4">Use your registered phone number to request a reset code.</p>

            <?php if ($error !== ''): ?><div class="alert alert-danger"><?= htmlspecialchars($error) ?></div><?php endif; ?>
            <?php if ($success !== ''): ?><div class="alert alert-success"><?= htmlspecialchars($success) ?></div><?php endif; ?>

            <?php if ($step === 1): ?>
                <form method="POST">
                    <input type="hidden" name="action" value="request_otp">
                    <div class="mb-3">
                        <label class="portal-label" for="phone">Phone Number</label>
                        <input type="text" id="phone" name="phone" class="portal-input" data-phone-input required>
                    </div>
                    <button type="submit" class="portal-btn-primary w-100">Send OTP</button>
                </form>
            <?php else: ?>
                <form method="POST">
                    <input type="hidden" name="action" value="reset_password">
                    <input type="hidden" name="phone" value="<?= htmlspecialchars($phone) ?>">
                    <div class="mb-3">
                        <label class="portal-label" for="otp_code">OTP Code</label>
                        <input type="text" id="otp_code" name="otp_code" class="portal-input" maxlength="6" required>
                    </div>
                    <div class="mb-3">
                        <label class="portal-label" for="new_password">New Password</label>
                        <input type="password" id="new_password" name="new_password" class="portal-input" required>
                    </div>
                    <div class="mb-3">
                        <label class="portal-label" for="confirm_password">Confirm Password</label>
                        <input type="password" id="confirm_password" name="confirm_password" data-confirm-password="new_password" class="portal-input" required>
                    </div>
                    <button type="submit" class="portal-btn-primary w-100">Reset Password</button>
                </form>
            <?php endif; ?>
            <div class="text-center mt-3"><a href="login.php">Back to Login</a></div>
        </div>
    </div>
    <script src="assets/js/portal.js"></script>
</body>
</html>
