<?php
require '../../db.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $token = $_POST['token'];
    $new_password = $_POST['pwd'];
    $confirm_password = $_POST['pwdc'];

    if ($new_password !== $confirm_password) {
        echo "Passwords do not match.";
        exit();
    }

    try {
        $stmt = $pdo->prepare("SELECT email FROM password_resets WHERE token = ?");
        $stmt->execute([$token]);
        $email = $stmt->fetchColumn();
    
        if ($email) {
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);

            $tables = ['users', 'property_users', 'dealer_admins'];

            $updated = false;
            foreach ($tables as $table) {
                $stmt = $pdo->prepare("UPDATE $table SET password = ? WHERE email = ?");
                $stmt->execute([$hashed_password, $email]);
        
                if ($stmt->rowCount() > 0) {
                    $updated = true;
                    break;
                }
            }
        
            if (!$updated) {
                echo "Something went wrong. Please Try Again!";
                exit;
            }

            $stmt = $pdo->prepare("DELETE FROM password_resets WHERE token = ?");
            $stmt->execute([$token]);
        
            echo "Your password has been successfully reset. You will now be redirected to the Login Page.";
            header("refresh:5;url=../../login.php");
        } else {
            echo "Invalid token.";
        }
    } catch (PDOException $e) {
        error_log("Database error: " . $e->getMessage());
        echo "A database error occurred. Please try again later.";
    }
    
}
?>
