<?php
/**
 * Test Password Change API
 * Use this to test the password change functionality
 */

// Start session
session_start();

// Simulate a logged-in manager
$_SESSION['manager_id'] = 1;  // Change this to your manager ID

header('Content-Type: application/json');

echo "Testing Password Change API\n";
echo "============================\n\n";

// Include config
require_once 'config.php';

// Check connection
if (!$conn) {
    die(json_encode(['error' => 'Database connection failed: ' . mysqli_connect_error()]));
}

if ($conn->connect_error) {
    die(json_encode(['error' => 'Connection error: ' . $conn->connect_error]));
}

$manager_id = $_SESSION['manager_id'];
echo "Manager ID: $manager_id\n";

// Test 1: Check if manager exists
echo "\nTest 1: Checking if manager exists...\n";
$stmt = $conn->prepare("SELECT id, name, email FROM managers WHERE id = ?");
$stmt->bind_param("i", $manager_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    $manager = $result->fetch_assoc();
    echo "✓ Manager found: " . $manager['name'] . " (" . $manager['email'] . ")\n";
} else {
    echo "✗ Manager not found\n";
    exit;
}

// Test 2: Check if password column exists
echo "\nTest 2: Checking password column...\n";
$stmt = $conn->prepare("SELECT password FROM managers WHERE id = ?");
$stmt->bind_param("i", $manager_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    if ($row['password']) {
        echo "✓ Password hash found (length: " . strlen($row['password']) . " chars)\n";
        echo "  Hash starts with: " . substr($row['password'], 0, 10) . "...\n";
    } else {
        echo "✗ Password is NULL\n";
    }
} else {
    echo "✗ Could not fetch password\n";
}

// Test 3: Test password verification
echo "\nTest 3: Testing password verification...\n";
$testPassword = 'testpass';  // Try with a simple password
echo "Testing password: $testPassword\n";

$stmt = $conn->prepare("SELECT password FROM managers WHERE id = ?");
$stmt->bind_param("i", $manager_id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();

if (password_verify($testPassword, $row['password'])) {
    echo "✓ Password matches!\n";
} else {
    echo "✗ Password does not match\n";
    echo "  Try using the current password from your login\n";
}

// Test 4: Test password hashing
echo "\nTest 4: Testing password hashing...\n";
$newPassword = 'NewPassword123';
$hashedPassword = password_hash($newPassword, PASSWORD_BCRYPT);
echo "✓ Password hashed successfully (length: " . strlen($hashedPassword) . " chars)\n";

// Test 5: Verify the hash
if (password_verify($newPassword, $hashedPassword)) {
    echo "✓ Hash verification successful\n";
} else {
    echo "✗ Hash verification failed\n";
}

echo "\n============================\n";
echo "All tests completed!\n";

$conn->close();
?>
