<?php
// /edenrms/pages/forgot_password.php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/email_helper.php';

$db = ec_db();
if (!$db instanceof mysqli) {
    die('DB connection failed');
}

if (!function_exists('h')) {
    function h($v): string {
        return htmlspecialchars((string)$v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

function fp_table_exists(mysqli $db, string $table): bool {
    if (function_exists('table_exists')) {
        return table_exists($db, $table);
    }
    $table = $db->real_escape_string($table);
    $rs = $db->query("SHOW TABLES LIKE '{$table}'");
    return $rs && $rs->num_rows > 0;
}

function fp_col_exists(mysqli $db, string $table, string $col): bool {
    if (function_exists('col_exists')) {
        return col_exists($db, $table, $col);
    }
    $table = $db->real_escape_string($table);
    $col   = $db->real_escape_string($col);
    $rs = $db->query("SHOW COLUMNS FROM `{$table}` LIKE '{$col}'");
    return $rs && $rs->num_rows > 0;
}

function fp_csrf_token(): string {
    if (empty($_SESSION['fp_csrf_token'])) {
        $_SESSION['fp_csrf_token'] = bin2hex(random_bytes(32));
    }
    return (string)$_SESSION['fp_csrf_token'];
}

function fp_base_url(): string {
    $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
        || ((int)($_SERVER['SERVER_PORT'] ?? 80) === 443);

    $scheme = $https ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';

    return $scheme . '://' . $host;
}

function fp_reset_url(string $token): string {
    return fp_base_url() . '/edenrms/pages/forgot_password.php?token=' . rawurlencode($token);
}



function fp_password_errors(string $password): array {
    $errors = [];

    if (strlen($password) < 8) {
        $errors[] = 'Password must be at least 8 characters.';
    }

    if (!preg_match('/[A-Z]/', $password)) {
        $errors[] = 'Password must contain at least one uppercase letter.';
    }

    if (!preg_match('/[a-z]/', $password)) {
        $errors[] = 'Password must contain at least one lowercase letter.';
    }

    if (!preg_match('/[0-9]/', $password)) {
        $errors[] = 'Password must contain at least one number.';
    }

    return $errors;
}

if (!fp_table_exists($db, 'users')) {
    die('Users table not found.');
}

$db->query("
    CREATE TABLE IF NOT EXISTS password_resets (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        token_hash VARCHAR(255) NOT NULL,
        expires_at DATETIME NOT NULL,
        used_at DATETIME NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX (user_id),
        INDEX (token_hash),
        INDEX (expires_at)
    )
");

$csrf = fp_csrf_token();

$mode = isset($_GET['token']) ? 'reset' : 'request';
$token = trim((string)($_GET['token'] ?? ''));

$errors = [];
$success = '';
$genericSentMessage = 'If that email exists in RMS, a password reset link has been sent. Please check your inbox.';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postedMode = (string)($_POST['mode'] ?? 'request');
    $postedToken = (string)($_POST['csrf_token'] ?? '');

    if (!hash_equals($csrf, $postedToken)) {
        $errors[] = 'Security token expired. Please refresh the page and try again.';
    }

    if (!$errors && $postedMode === 'request') {
        $email = trim((string)($_POST['email'] ?? ''));

        if ($email === '') {
            $errors[] = 'Email is required.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'Please enter a valid email address.';
        }

        if (!$errors) {
            $hasActive = fp_col_exists($db, 'users', 'active');

            $sql = $hasActive
                ? "SELECT id, name, email FROM users WHERE email = ? AND active = 1 LIMIT 1"
                : "SELECT id, name, email FROM users WHERE email = ? LIMIT 1";

            $st = $db->prepare($sql);
            $st->bind_param('s', $email);
            $st->execute();
            $user = $st->get_result()->fetch_assoc();
            $st->close();

            if ($user) {
                $rawToken = bin2hex(random_bytes(32));
                $tokenHash = hash('sha256', $rawToken);
                $expiresAt = date('Y-m-d H:i:s', time() + (30 * 60));
                $userId = (int)$user['id'];

                $st = $db->prepare("UPDATE password_resets SET used_at = NOW() WHERE user_id = ? AND used_at IS NULL");
                if ($st) {
                    $st->bind_param('i', $userId);
                    $st->execute();
                    $st->close();
                }

                $st = $db->prepare("
                    INSERT INTO password_resets (user_id, token_hash, expires_at)
                    VALUES (?, ?, ?)
                ");

                if ($st) {
                    $st->bind_param('iss', $userId, $tokenHash, $expiresAt);
                    $st->execute();
                    $st->close();

                    $resetUrl = fp_reset_url($rawToken);
                    $name = h($user['name'] ?? 'User');

                    $subject = 'Reset your Eden RMS password';
                    $html = '
                        <div style="font-family:Arial,sans-serif;background:#f6f7fb;padding:24px;">
                            <div style="max-width:560px;margin:auto;background:#ffffff;border:1px solid #e5e7eb;border-radius:16px;padding:24px;">
                                <h2 style="margin:0 0 12px;color:#111827;">Password Reset Request</h2>
                                <p style="color:#334155;">Hello ' . $name . ',</p>
                                <p style="color:#334155;">We received a request to reset your Eden RMS password.</p>
                                <p style="margin:24px 0;">
                                    <a href="' . h($resetUrl) . '" style="background:#111827;color:#ffffff;text-decoration:none;padding:12px 18px;border-radius:999px;display:inline-block;">
                                        Reset Password
                                    </a>
                                </p>
                                <p style="color:#64748b;font-size:13px;">This link will expire in 30 minutes.</p>
                                <p style="color:#64748b;font-size:13px;">If you did not request this, you can ignore this email.</p>
                            </div>
                        </div>
                    ';

                    $emailResult = rms_send_email(
    (string)$user['email'],
    $subject,
    $html,
    (string)($user['name'] ?? '')
);

if (!$emailResult['ok']) {
    error_log('Forgot password email failed: ' . $emailResult['message']);
}
                }
            }

            unset($_SESSION['fp_csrf_token']);
            $success = $genericSentMessage;
            $csrf = fp_csrf_token();
        }
    }

    if (!$errors && $postedMode === 'reset') {
        $rawToken = trim((string)($_POST['reset_token'] ?? ''));
        $newPassword = (string)($_POST['new_password'] ?? '');
        $confirmPassword = (string)($_POST['confirm_password'] ?? '');

        if ($rawToken === '') {
            $errors[] = 'Invalid reset token.';
        }

        if ($newPassword === '') {
            $errors[] = 'New password is required.';
        }

        if ($newPassword !== $confirmPassword) {
            $errors[] = 'New password and confirm password do not match.';
        }

        if (!$errors) {
            $errors = array_merge($errors, fp_password_errors($newPassword));
        }

        if (!$errors) {
            $tokenHash = hash('sha256', $rawToken);

            $st = $db->prepare("
                SELECT pr.id, pr.user_id, u.email, u.name
                FROM password_resets pr
                INNER JOIN users u ON u.id = pr.user_id
                WHERE pr.token_hash = ?
                  AND pr.used_at IS NULL
                  AND pr.expires_at >= NOW()
                LIMIT 1
            ");
            $st->bind_param('s', $tokenHash);
            $st->execute();
            $resetRow = $st->get_result()->fetch_assoc();
            $st->close();

            if (!$resetRow) {
                $errors[] = 'This reset link is invalid or expired. Please request a new link.';
            } else {
                $hash = password_hash($newPassword, PASSWORD_DEFAULT);
                $resetId = (int)$resetRow['id'];
                $resetUserId = (int)$resetRow['user_id'];

                $sets = ['password_hash = ?'];
                if (fp_col_exists($db, 'users', 'updated_at')) {
                    $sets[] = 'updated_at = NOW()';
                }

                $db->begin_transaction();

                try {
                    $sql = "UPDATE users SET " . implode(', ', $sets) . " WHERE id = ? LIMIT 1";
                    $st = $db->prepare($sql);
                    if (!$st) {
                        throw new Exception($db->error);
                    }
                    $st->bind_param('si', $hash, $resetUserId);
                    $st->execute();
                    $st->close();

                    $st = $db->prepare("UPDATE password_resets SET used_at = NOW() WHERE id = ? LIMIT 1");
                    if (!$st) {
                        throw new Exception($db->error);
                    }
                    $st->bind_param('i', $resetId);
                    $st->execute();
                    $st->close();

                    $db->commit();

                    unset($_SESSION['fp_csrf_token']);
                    $success = 'Password reset successfully. You can now login with your new password.';
                    $mode = 'done';
                } catch (Throwable $e) {
                    $db->rollback();
                    $errors[] = 'Password reset failed. Please try again.';
                }
            }
        }
    }
}

if ($mode === 'reset' && $token === '') {
    $mode = 'request';
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Forgot Password — Eden RMS</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">

    <style>
        :root{
            --bg:#f6f7fb;
            --card:#ffffff;
            --border:#e5e7eb;
            --text:#0f172a;
            --muted:#64748b;
            --primary:#111827;
        }

        body{
            min-height:100vh;
            margin:0;
            font-family:system-ui,-apple-system,"Segoe UI",Roboto,Arial,sans-serif;
            background:var(--bg);
            color:var(--text);
            display:flex;
            align-items:center;
            justify-content:center;
            padding:24px;
        }

        .auth-wrap{
            width:100%;
            max-width:440px;
        }

        .auth-card{
            background:var(--card);
            border:1px solid var(--border);
            border-radius:20px;
            padding:30px;
            box-shadow:0 18px 45px rgba(15,23,42,.08);
        }

        .brand-row{
            display:flex;
            align-items:center;
            gap:12px;
            padding-bottom:16px;
            margin-bottom:18px;
            border-bottom:1px solid var(--border);
        }

        .logo-box{
            width:48px;
            height:48px;
            border-radius:14px;
            border:1px solid var(--border);
            background:#fff;
            display:flex;
            align-items:center;
            justify-content:center;
            overflow:hidden;
        }

        .logo-box img{
            width:40px;
            height:40px;
            object-fit:contain;
        }

        .brand-title{
            font-weight:900;
            letter-spacing:.14em;
            font-size:.86rem;
            margin:0;
        }

        .brand-sub{
            margin:3px 0 0;
            color:var(--muted);
            font-size:.78rem;
        }

        .form-control{
            border-radius:13px;
            padding:.78rem .9rem;
            border:1px solid var(--border);
        }

        .form-control:focus{
            border-color:rgba(17,24,39,.55);
            box-shadow:0 0 0 .18rem rgba(17,24,39,.10);
        }

        .btn-dark{
            background:var(--primary);
            border-color:var(--primary);
            border-radius:999px;
            padding:.78rem 1rem;
            font-weight:700;
        }

        .small-link{
            color:#111827;
            text-decoration:none;
            font-weight:700;
            font-size:.9rem;
        }

        .small-link:hover{
            text-decoration:underline;
        }
    </style>
</head>
<body>

<div class="auth-wrap">
    <div class="auth-card">
        <div class="brand-row">
            <div class="logo-box">
                <img src="/edenrms/assets/img/eden-logo.png.JPG"
                     alt="Eden"
                     onerror="this.onerror=null;this.style.display='none';">
            </div>
            <div>
                <p class="brand-title">EDEN CAMPUS</p>
                <p class="brand-sub">Resource Management System</p>
            </div>
        </div>

        <?php if ($mode === 'request'): ?>
            <h4 class="fw-bold mb-1">Forgot Password</h4>
            <p class="text-muted small mb-4">
                Enter your RMS email address. We will send a password reset link if your account exists.
            </p>
        <?php elseif ($mode === 'reset'): ?>
            <h4 class="fw-bold mb-1">Reset Password</h4>
            <p class="text-muted small mb-4">
                Enter your new password below.
            </p>
        <?php else: ?>
            <h4 class="fw-bold mb-1">Password Updated</h4>
            <p class="text-muted small mb-4">
                You can now login to Eden RMS.
            </p>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="alert alert-success small">
                <?= h($success) ?>
            </div>
        <?php endif; ?>

        <?php if ($errors): ?>
            <div class="alert alert-danger small">
                <strong>Please check:</strong>
                <ul class="mb-0 mt-1">
                    <?php foreach ($errors as $e): ?>
                        <li><?= h($e) ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>

        <?php if ($mode === 'request'): ?>
            <form method="post" autocomplete="off">
                <input type="hidden" name="mode" value="request">
                <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">

                <div class="mb-3">
                    <label class="form-label fw-semibold small">Email Address</label>
                    <input type="email" name="email" class="form-control" required
                           placeholder="you@example.com">
                </div>

                <div class="d-grid mb-3">
                    <button type="submit" class="btn btn-dark">
                        <i class="bi bi-envelope me-1"></i> Send Reset Link
                    </button>
                </div>
            </form>
        <?php elseif ($mode === 'reset'): ?>
            <form method="post" autocomplete="off">
                <input type="hidden" name="mode" value="reset">
                <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
                <input type="hidden" name="reset_token" value="<?= h($token) ?>">

                <div class="mb-3">
                    <label class="form-label fw-semibold small">New Password</label>
                    <div class="input-group">
                        <input type="password" name="new_password" id="new_password"
                               class="form-control rounded-start-3" required minlength="8">
                        <button type="button" class="btn btn-outline-secondary rounded-end-3"
                                onclick="togglePass('new_password', this)">
                            <i class="bi bi-eye"></i>
                        </button>
                    </div>
                    <div class="form-text">
                        Minimum 8 characters, uppercase, lowercase and number.
                    </div>
                </div>

                <div class="mb-4">
                    <label class="form-label fw-semibold small">Confirm Password</label>
                    <div class="input-group">
                        <input type="password" name="confirm_password" id="confirm_password"
                               class="form-control rounded-start-3" required minlength="8">
                        <button type="button" class="btn btn-outline-secondary rounded-end-3"
                                onclick="togglePass('confirm_password', this)">
                            <i class="bi bi-eye"></i>
                        </button>
                    </div>
                </div>

                <div class="d-grid mb-3">
                    <button type="submit" class="btn btn-dark">
                        <i class="bi bi-check2-circle me-1"></i> Reset Password
                    </button>
                </div>
            </form>
        <?php endif; ?>

        <div class="text-center mt-3">
            <a href="/edenrms/login.php" class="small-link">
                <i class="bi bi-arrow-left me-1"></i> Back to Login
            </a>
        </div>
    </div>
</div>

<script>
function togglePass(id, btn) {
    const input = document.getElementById(id);
    const icon = btn.querySelector('i');
    if (!input) return;

    if (input.type === 'password') {
        input.type = 'text';
        if (icon) icon.className = 'bi bi-eye-slash';
    } else {
        input.type = 'password';
        if (icon) icon.className = 'bi bi-eye';
    }
}
</script>

</body>
</html>