<?php
session_start();
require_once "config/database.php";

$database = new Database();
$db = $database->getConnection();

if (!$db) {
    die("Database connection failed.");
}

$message = "";
$message_type = "";
$token = $_GET['token'] ?? '';

if ($token === '') {
    die("Invalid reset link.");
}

$hashedToken = hash('sha256', $token);

$stmt = $db->prepare("
    SELECT pr.id, pr.user_id, pr.expires_at, pr.used, u.username
    FROM password_resets pr
    INNER JOIN users u ON u.id = pr.user_id
    WHERE pr.token = :token
    LIMIT 1
");
$stmt->bindParam(":token", $hashedToken);
$stmt->execute();
$reset = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$reset) {
    die("Invalid reset link.");
}

if ((int)$reset['used'] === 1 || strtotime($reset['expires_at']) < time()) {
    die("This reset link is expired or already used.");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $password = trim($_POST['password'] ?? '');
    $confirm_password = trim($_POST['confirm_password'] ?? '');

    if ($password === '' || $confirm_password === '') {
        $message = "Please fill all fields.";
        $message_type = "error";
    } elseif ($password !== $confirm_password) {
        $message = "Passwords do not match.";
        $message_type = "error";
    } elseif (strlen($password) < 6) {
        $message = "Password must be at least 6 characters.";
        $message_type = "error";
    } else {
        $newHashedPassword = password_hash($password, PASSWORD_DEFAULT);

        $updateUser = $db->prepare("UPDATE users SET password = :password WHERE id = :user_id");
        $updateUser->bindParam(":password", $newHashedPassword);
        $updateUser->bindParam(":user_id", $reset['user_id']);

        $markUsed = $db->prepare("UPDATE password_resets SET used = 1 WHERE id = :id");
        $markUsed->bindParam(":id", $reset['id']);

        if ($updateUser->execute() && $markUsed->execute()) {
            $message = "Password has been reset successfully. You can login now.";
            $message_type = "success";
        } else {
            $message = "Failed to reset password.";
            $message_type = "error";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reset Password - DocuTrack</title>
    <style>
        body {
            margin: 0;
            background: linear-gradient(135deg, #f4f7fb 0%, #e9eef6 100%);
            font-family: Arial, sans-serif;
        }

        .page {
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 24px;
        }

        .card {
            width: 100%;
            max-width: 420px;
            background: #fff;
            padding: 32px;
            border-radius: 20px;
            box-shadow: 0 20px 50px rgba(16, 24, 40, 0.12);
        }

        h2 {
            margin-top: 0;
            margin-bottom: 8px;
        }

        p.subtext {
            color: #667085;
            margin-bottom: 24px;
        }

        .form-group {
            margin-bottom: 18px;
        }

        .form-group label {
            display: block;
            font-weight: 600;
            margin-bottom: 8px;
            color: #344054;
        }

        .form-group input {
            width: 100%;
            box-sizing: border-box;
            padding: 12px 14px;
            border: 1px solid #d0d5dd;
            border-radius: 12px;
            font-size: 15px;
        }

        .alert-box {
            margin-bottom: 18px;
            padding: 12px 14px;
            border-radius: 12px;
            font-size: 14px;
        }

        .alert-danger {
            background: #fef3f2;
            color: #b42318;
            border: 1px solid #fecdca;
        }

        .alert-success {
            background: #ecfdf3;
            color: #166534;
            border: 1px solid #abefc6;
        }

        button {
            width: 100%;
            padding: 12px 14px;
            border: none;
            border-radius: 12px;
            background: #2563eb;
            color: white;
            font-size: 15px;
            cursor: pointer;
        }

        .back-link {
            display: block;
            text-align: center;
            margin-top: 16px;
            color: #2563eb;
            text-decoration: none;
            font-weight: 600;
        }
    </style>
</head>
<body>
    <div class="page">
        <div class="card">
            <h2>Reset Password</h2>
            <?php if ($message_type !== 'success'): ?>
                <p class="subtext">
                    Set a new password for <?php echo htmlspecialchars($reset['username']); ?>.
                </p>
            <?php endif; ?>

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

            <?php if ($message_type !== 'success'): ?>
                <form method="POST">
                    <div class="form-group">
                        <label for="password">New Password</label>
                        <input
                            type="password"
                            name="password"
                            id="password"
                            placeholder="Enter new password"
                            required
                        >
                    </div>

                    <div class="form-group">
                        <label for="confirm_password">Confirm Password</label>
                        <input
                            type="password"
                            name="confirm_password"
                            id="confirm_password"
                            placeholder="Confirm new password"
                            required
                        >
                    </div>

                    <button type="submit">Reset Password</button>
                </form>
            <?php endif; ?>

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