<?php
session_start();
header('Content-Type: application/json');

// Enable error logging
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/password_debug.log');

if (!isset($_SESSION['user_id'])) {
    error_log("Password Update: No user session");
    echo json_encode(['status' => 401, 'error' => 'Unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    error_log("Password Update: Invalid method " . $_SERVER['REQUEST_METHOD']);
    echo json_encode(['status' => 405, 'error' => 'Method not allowed']);
    exit;
}

// Log received data
error_log("Password Update: User ID: " . $_SESSION['user_id']);
error_log("Password Update: POST data received: " . print_r($_POST, true));

$current_password = $_POST['current_password'] ?? '';
$new_password = $_POST['password'] ?? '';
$password_confirmation = $_POST['password_confirmation'] ?? '';

// Validation
if (empty($current_password) || empty($new_password) || empty($password_confirmation)) {
    error_log("Password Update: Empty fields detected");
    echo json_encode(['status' => 400, 'error' => 'All fields are required']);
    exit;
}

if ($new_password !== $password_confirmation) {
    error_log("Password Update: Passwords don't match");
    echo json_encode(['status' => 400, 'error' => 'New passwords do not match']);
    exit;
}

if (strlen($new_password) < 8) {
    error_log("Password Update: Password too short");
    echo json_encode(['status' => 400, 'error' => 'Password must be at least 8 characters']);
    exit;
}

try {
    $pdo = new PDO("mysql:host=localhost;dbname=liongate;charset=utf8mb4", "root", "", [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);

    // Get current password from database
    $stmt = $pdo->prepare("SELECT password FROM users WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $_SESSION['user_id']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        error_log("Password Update: User not found for ID: " . $_SESSION['user_id']);
        echo json_encode(['status' => 404, 'error' => 'User not found']);
        exit;
    }

    $db_password = $user['password'];
    
    // Log password details (remove in production!)
    error_log("Password Update: DB password length: " . strlen($db_password));
    error_log("Password Update: DB password starts with: " . substr($db_password, 0, 10) . "...");
    error_log("Password Update: Current password provided length: " . strlen($current_password));

    $password_valid = false;

    // Check if password is hashed
    if (strpos($db_password, '$2y$') === 0 || strpos($db_password, '$2a$') === 0) {
        error_log("Password Update: Detected HASHED password");
        $password_valid = password_verify($current_password, $db_password);
        error_log("Password Update: password_verify result: " . ($password_valid ? 'TRUE' : 'FALSE'));
    } else {
        error_log("Password Update: Detected PLAIN TEXT password");
        $password_valid = ($current_password === $db_password);
        error_log("Password Update: Direct comparison result: " . ($password_valid ? 'TRUE' : 'FALSE'));
        
        // Debug: Show what we're comparing (first 3 chars only for security)
        error_log("Password Update: Comparing '" . substr($current_password, 0, 3) . "***' with '" . substr($db_password, 0, 3) . "***'");
    }

    if (!$password_valid) {
        error_log("Password Update: INVALID PASSWORD");
        echo json_encode(['status' => 400, 'error' => 'Current password is incorrect']);
        exit;
    }

    // Hash and update new password
    $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
    
    $update = $pdo->prepare("UPDATE users SET password = :password WHERE id = :id");
    $update->execute([
        ':password' => $hashed_password,
        ':id' => $_SESSION['user_id']
    ]);

    error_log("Password Update: SUCCESS - Password updated for user " . $_SESSION['user_id']);
    echo json_encode(['status' => 200, 'success' => 'Password updated successfully']);

} catch (PDOException $e) {
    error_log("Password Update: Database error: " . $e->getMessage());
    echo json_encode(['status' => 500, 'error' => 'Database error: ' . $e->getMessage()]);
}
?>