<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once "../config/db.php";
$message = "";

// Pastikan token ada
if (!isset($_GET['token'])) {
    die("Invalid request.");
}

$token = $_GET['token'];

// Check token dari database
$sql = "SELECT * FROM password_resets WHERE token = ?";
$stmt = mysqli_prepare($conn, $sql);
if (!$stmt) die("SQL Error: " . mysqli_error($conn));

mysqli_stmt_bind_param($stmt, "s", $token);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

if (!$row = mysqli_fetch_assoc($result)) {
    die("Invalid or expired token.");
}

// Check expiry
if (strtotime($row['expiry']) < time()) {
    // Delete expired token
    $del = mysqli_prepare($conn, "DELETE FROM password_resets WHERE user_id = ?");
    mysqli_stmt_bind_param($del, "i", $row['user_id']);
    mysqli_stmt_execute($del);
    die("Token expired.");
}

$user_id = $row['user_id'];

// Handle reset password
if (isset($_POST['reset_password'])) {
    if (empty($_POST['password']) || empty($_POST['confirm_password'])) {
        $message = "Both fields are required.";
    } elseif ($_POST['password'] !== $_POST['confirm_password']) {
        $message = "Passwords do not match.";
    } else {
        $new_password = password_hash($_POST['password'], PASSWORD_DEFAULT);

        $update = "UPDATE users SET password=? WHERE id=?";
        $stmt2 = mysqli_prepare($conn, $update);
        if (!$stmt2) die("SQL Error: " . mysqli_error($conn));

        mysqli_stmt_bind_param($stmt2, "si", $new_password, $user_id);

        if (mysqli_stmt_execute($stmt2)) {
            // Delete token after success
            $delToken = mysqli_prepare($conn, "DELETE FROM password_resets WHERE user_id = ?");
            mysqli_stmt_bind_param($delToken, "i", $user_id);
            mysqli_stmt_execute($delToken);

            header("Location: login.php?reset=success");
            exit();
        } else {
            $message = "Error updating password.";
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Reset Password - QRCareTrack</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        * { box-sizing:border-box; font-family:'Segoe UI', sans-serif; }
        body {
            margin:0;
            height:100vh;
            background: url('../assets/background.png') no-repeat center center/cover;
            display:flex;
            justify-content:center;
            align-items:center;
        }
        .card {
            width:400px;
            background:#fff;
            padding:40px 35px;
            border-radius:12px;
            box-shadow:0 15px 35px rgba(0,0,0,0.15);
            text-align:center;
        }
        .logo { width:80px; margin-bottom:20px; }
        h2 { margin-bottom:25px; font-weight:600; color:#333; }
        .form-group { text-align:left; margin-bottom:18px; }
        label { font-size:14px; color:#444; display:block; margin-bottom:6px; }
        input { width:100%; padding:10px 12px; border:1px solid #ccc; border-radius:6px; font-size:14px; transition:0.2s; }
        input:focus { border-color:#2bbbad; outline:none; box-shadow:0 0 0 2px rgba(43,187,173,0.2); }
        .btn { width:100%; padding:11px; background-color:#2bbbad; border:none; border-radius:25px; color:white; font-size:15px; cursor:pointer; transition:0.2s; margin-top:10px; }
        .btn:hover { background-color:#239c92; }
        .message { background:#e8f8f5; color:#1d8348; padding:8px; border-radius:5px; margin-bottom:15px; font-size:13px; }
        .back { margin-top:15px; font-size:13px; }
        .back a { text-decoration:none; color:#666; }
        .back a:hover { text-decoration:underline; }
        @media (max-width:480px) { .card { width:90%; padding:30px 20px; } }
    </style>
</head>
<body>

<div class="card">
    <img src="../assets/logo.png" class="logo" alt="Logo">
    <h2>Reset Password</h2>

    <?php if (!empty($message)) : ?>
        <div class="message"><?php echo $message; ?></div>
    <?php endif; ?>

    <form method="POST">
        <div class="form-group">
            <label>New Password</label>
            <input type="password" name="password" required>
        </div>
        <div class="form-group">
            <label>Confirm Password</label>
            <input type="password" name="confirm_password" required>
        </div>
        <button type="submit" name="reset_password" class="btn">Reset Password</button>
    </form>

    <div class="back">
        <a href="login.php">Back to Login</a>
    </div>
</div>

</body>
</html>