<?php
header('Content-Type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', 1);

$response = ['success' => false, 'message' => ''];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['token']) && isset($_POST['email']) && isset($_POST['new_password']) && isset($_POST['confirm_password'])) {
    $token = trim($_POST['token']);
    $email = trim($_POST['email']);
    $newPassword = trim($_POST['new_password']);
    $confirmPassword = trim($_POST['confirm_password']);

    // Validate passwords
    if (empty($newPassword) || empty($confirmPassword)) {
        $response['message'] = 'Both password fields are required.';
        echo json_encode($response);
        exit();
    }
    
    if ($newPassword !== $confirmPassword) {
        $response['message'] = 'Passwords do not match.';
        echo json_encode($response);
        exit();
    }
    
    // Validate password strength: min 8 chars, must contain letters, numbers, and symbols
    if (strlen($newPassword) < 8) {
        $response['message'] = 'Password must be at least 8 characters long';
        echo json_encode($response);
        exit();
    }
    if (!preg_match('/[a-zA-Z]/', $newPassword)) {
        $response['message'] = 'Password must contain at least one letter';
        echo json_encode($response);
        exit();
    }
    if (!preg_match('/[0-9]/', $newPassword)) {
        $response['message'] = 'Password must contain at least one number';
        echo json_encode($response);
        exit();
    }
    if (!preg_match('/[!@#$%^&*()_+\-=\[\]{};:\'",.<>?\/\\|`~]/', $newPassword)) {
        $response['message'] = 'Password must contain at least one special character (!@#$%^&* etc)';
        echo json_encode($response);
        exit();
    }

    $server = "localhost";
    $username = "root";
    $password = "";
    $database = "login-table";

    $conn = new mysqli($server, $username, $password, $database);
    if ($conn->connect_error) {
        $response['message'] = 'Database connection error';
        echo json_encode($response);
        exit();
    }
    $conn->set_charset('utf8mb4');

    // Verify token ONLY (more reliable than matching email)
    $stmt = $conn->prepare("SELECT `sno`, `reset_expiry` FROM `login-t` WHERE `reset_token` = ?");
    if (!$stmt) {
        $response['message'] = 'Database error: ' . $conn->error;
        echo json_encode($response);
        exit();
    }
    $stmt->bind_param("s", $token);
    if (!$stmt->execute()) {
        $response['message'] = 'Query execution error: ' . $stmt->error;
        echo json_encode($response);
        exit();
    }
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $userId = $row['sno'];
        $expiry = $row['reset_expiry'];
        
        // Check if token is expired
        if (empty($expiry) || strtotime($expiry) < time()) {
            $response['message'] = 'Password reset link has expired. Please request a new one.';
            $stmt->close();
            $conn->close();
            echo json_encode($response);
            exit();
        }

        $updateStmt = $conn->prepare("UPDATE `login-t` SET `password` = ?, `reset_token` = NULL, `reset_expiry` = NULL WHERE `sno` = ?");
        if (!$updateStmt) {
            $response['message'] = 'Database error: ' . $conn->error;
            echo json_encode($response);
            exit();
        }
        $updateStmt->bind_param("si", $newPassword, $userId);
        
        if ($updateStmt->execute()) {
            $response['success'] = true;
            $response['message'] = 'Password reset successfully. Please login with your new password.';
        } else {
            $response['message'] = 'Error updating password: ' . $updateStmt->error;
        }
        $updateStmt->close();
    } else {
        $response['message'] = 'Invalid reset token. The token does not exist or has been used.';
    }

    $stmt->close();
    $conn->close();
}

echo json_encode($response);
?>
