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

$conn  = getDBConnection();
$phone = preg_replace('/\D+/', '', trim((string) ($_GET['phone'] ?? $_POST['phone'] ?? '')));
$otp   = trim((string) ($_GET['otp'] ?? ''));
$error = '';
$step  = 'verify';   // verify | new_password | success | expired

// ── URL-based OTP: validate immediately ──────────────────────────────────
if ($phone !== '' && $otp !== '' && $_SERVER['REQUEST_METHOD'] !== 'POST') {
    if ($conn instanceof mysqli) {
        $stmt = $conn->prepare(
            "SELECT id FROM parent_accounts
             WHERE phone = ? AND otp_code = ?
             AND otp_expires > NOW() AND is_active = 1
             LIMIT 1"
        );
        $stmt->bind_param('ss', $phone, $otp);
        $stmt->execute();
        $valid = $stmt->get_result()->num_rows > 0;
        $stmt->close();

        if ($valid) {
            $step = 'new_password';
            $_SESSION['otp_reset_phone'] = $phone;
            $_SESSION['otp_reset_code']  = $otp;
        } else {
            $error = 'This reset link has expired or is invalid. Please request a new one.';
            $step  = 'expired';
        }
    } else {
        $error = 'Database unavailable. Please try again.';
        $step  = 'expired';
    }
}

// ── Manual OTP verify form submission ────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'verify_otp') {
    $phone = preg_replace('/\D+/', '', trim((string) ($_POST['phone'] ?? '')));
    $otp   = trim((string) ($_POST['otp_code'] ?? ''));

    if ($phone === '' || $otp === '') {
        $error = 'Please enter your phone number and OTP code.';
        $step  = 'verify';
    } elseif (!$conn instanceof mysqli) {
        $error = 'Database unavailable.';
        $step  = 'verify';
    } else {
        $stmt = $conn->prepare(
            "SELECT id FROM parent_accounts
             WHERE phone = ? AND otp_code = ?
             AND otp_expires > NOW() AND is_active = 1
             LIMIT 1"
        );
        $stmt->bind_param('ss', $phone, $otp);
        $stmt->execute();
        $valid = $stmt->get_result()->num_rows > 0;
        $stmt->close();

        if ($valid) {
            $step = 'new_password';
            $_SESSION['otp_reset_phone'] = $phone;
            $_SESSION['otp_reset_code']  = $otp;
        } else {
            $error = 'Invalid or expired OTP code. Please request a new one.';
            $step  = 'verify';
        }
    }
}

// ── New password submission ───────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'set_password') {
    $phone = $_SESSION['otp_reset_phone'] ?? '';
    $otp   = $_SESSION['otp_reset_code']  ?? '';
    $new   = (string) ($_POST['new_password']     ?? '');
    $conf  = (string) ($_POST['confirm_password'] ?? '');

    if ($phone === '' || $otp === '') {
        $error = 'Session expired. Please request a new reset link.';
        $step  = 'expired';
    } elseif (strlen($new) < 6) {
        $error = 'Password must be at least 6 characters.';
        $step  = 'new_password';
    } elseif ($new !== $conf) {
        $error = 'Passwords do not match.';
        $step  = 'new_password';
    } elseif (!$conn instanceof mysqli) {
        $error = 'Database unavailable.';
        $step  = 'new_password';
    } else {
        // Final OTP re-check before commit
        $stmt = $conn->prepare(
            "SELECT id FROM parent_accounts
             WHERE phone = ? AND otp_code = ?
             AND otp_expires > NOW() AND is_active = 1
             LIMIT 1"
        );
        $stmt->bind_param('ss', $phone, $otp);
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if (!$row) {
            $error = 'Reset link has expired. Please request a new one.';
            unset($_SESSION['otp_reset_phone'], $_SESSION['otp_reset_code']);
            $step = 'expired';
        } else {
            $hash  = password_hash($new, PASSWORD_BCRYPT);
            $stmt2 = $conn->prepare(
                "UPDATE parent_accounts
                 SET password_hash = ?, otp_code = NULL, otp_expires = NULL
                 WHERE id = ?"
            );
            $stmt2->bind_param('si', $hash, $row['id']);
            $stmt2->execute();
            $stmt2->close();
            unset($_SESSION['otp_reset_phone'], $_SESSION['otp_reset_code']);
            $step = 'success';
        }
    }
}

// Keep step as new_password if session still valid after POST error
if ($step === 'verify' && isset($_SESSION['otp_reset_phone'])) {
    $step = 'new_password';
}

$school_name = '';
$school_logo = '';
if ($conn instanceof mysqli) {
    $r = $conn->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('school_name','school_logo')");
    if ($r) {
        while ($row = $r->fetch_assoc()) {
            if ($row['setting_key'] === 'school_name') $school_name = $row['setting_value'];
            if ($row['setting_key'] === 'school_logo') $school_logo = $row['setting_value'];
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Reset Password — <?= htmlspecialchars($school_name ?: 'EduTrack') ?></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">

    <!-- Logo / branding -->
    <div class="portal-auth-logo">
      <?php if ($school_logo !== '' && file_exists('../' . $school_logo)): ?>
        <img src="../<?= htmlspecialchars($school_logo) ?>" alt="Logo"
             style="max-height:64px;object-fit:contain">
      <?php else: ?>
        <i class="fas fa-lock"></i>
      <?php endif; ?>
    </div>
    <h1 class="h4 text-center mb-1">Reset Password</h1>
    <p class="portal-subtitle text-center mb-4">
      <?= htmlspecialchars($school_name ?: 'EduTrack Parent Portal') ?>
    </p>

    <?php if ($error !== ''): ?>
      <div class="alert alert-danger d-flex align-items-center gap-2">
        <i class="fas fa-exclamation-triangle"></i>
        <?= htmlspecialchars($error) ?>
      </div>
    <?php endif; ?>

    <?php if ($step === 'verify'): ?>
    <!-- ── Step 1: Enter phone + OTP ── -->
    <p class="small text-muted mb-3">
      Enter the phone number used for your account and the 6-digit OTP
      sent to you via SMS.
    </p>
    <form method="POST">
      <input type="hidden" name="action" value="verify_otp">
      <div class="mb-3">
        <label class="portal-label">Phone Number</label>
        <input type="text" name="phone" class="portal-input"
               placeholder="e.g. 0244123456"
               value="<?= htmlspecialchars($phone) ?>" required>
      </div>
      <div class="mb-3">
        <label class="portal-label">OTP Code</label>
        <input type="text" name="otp_code" class="portal-input"
               placeholder="6-digit code" maxlength="10"
               inputmode="numeric" autocomplete="one-time-code" required>
      </div>
      <button type="submit" class="portal-btn-primary w-100">Verify OTP</button>
    </form>
    <div class="text-center mt-3">
      <a href="forgot_password.php" class="small">Didn't receive an OTP? Request one</a>
    </div>

    <?php elseif ($step === 'new_password'): ?>
    <!-- ── Step 2: Set new password ── -->
    <p class="small text-muted mb-3">
      Your OTP has been verified. Enter your new password below.
    </p>
    <form method="POST">
      <input type="hidden" name="action" value="set_password">
      <div class="mb-3">
        <label class="portal-label">New Password</label>
        <input type="password" id="newPw" name="new_password"
               class="portal-input" minlength="6"
               placeholder="At least 6 characters" required>
      </div>
      <div class="mb-3">
        <label class="portal-label">Confirm New Password</label>
        <input type="password" id="confPw" name="confirm_password"
               class="portal-input" placeholder="Repeat password" required>
        <div id="pwMismatch" class="text-danger small mt-1" style="display:none">
          Passwords do not match.
        </div>
      </div>
      <button type="submit" class="portal-btn-primary w-100" id="submitBtn">
        <i class="fas fa-key me-1"></i> Set New Password
      </button>
    </form>

    <?php elseif ($step === 'success'): ?>
    <!-- ── Success ── -->
    <div class="text-center py-3">
      <div style="width:72px;height:72px;border-radius:50%;background:#d1fae5;
                  display:flex;align-items:center;justify-content:center;margin:0 auto 1rem">
        <i class="fas fa-check-circle fa-2x" style="color:#059669"></i>
      </div>
      <h5 class="fw-bold text-success mb-2">Password Changed!</h5>
      <p class="text-muted small mb-4">
        Your password has been updated successfully.
        You can now sign in with your new password.
      </p>
      <a href="login.php" class="portal-btn-primary d-block text-center">
        <i class="fas fa-sign-in-alt me-1"></i> Sign In
      </a>
    </div>

    <?php elseif ($step === 'expired'): ?>
    <!-- ── Expired / invalid ── -->
    <div class="text-center py-3">
      <div style="width:72px;height:72px;border-radius:50%;background:#fee2e2;
                  display:flex;align-items:center;justify-content:center;margin:0 auto 1rem">
        <i class="fas fa-exclamation-circle fa-2x" style="color:#dc2626"></i>
      </div>
      <h5 class="fw-bold text-danger mb-2">Link Expired</h5>
      <p class="text-muted small mb-4">
        This reset link has expired or is no longer valid.
        Please request a new one.
      </p>
      <a href="forgot_password.php" class="portal-btn-primary d-block text-center">
        <i class="fas fa-redo me-1"></i> Request New Reset Link
      </a>
    </div>

    <?php endif; ?>

    <?php if (in_array($step, ['verify', 'new_password'])): ?>
    <div class="text-center mt-4">
      <a href="login.php" class="small portal-muted">
        <i class="fas fa-arrow-left me-1"></i>Back to Sign In
      </a>
    </div>
    <?php endif; ?>

  </div>
</div>

<script>
// Live password match check
const newPw  = document.getElementById('newPw');
const confPw = document.getElementById('confPw');
const warn   = document.getElementById('pwMismatch');
const btn    = document.getElementById('submitBtn');
if (confPw) {
    confPw.addEventListener('input', () => {
        const mismatch = newPw.value !== confPw.value && confPw.value !== '';
        warn.style.display = mismatch ? 'block' : 'none';
        if (btn) btn.disabled = mismatch;
    });
}
</script>
<script src="assets/js/portal.js"></script>
</body>
</html>
