<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { exit(0); }
header('Content-Type: application/json');

include_once '../config/Database.php';
include_once '../middleware/auth.php';

$database = new Database();
$db = $database->connect();
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'PUT') {
    $user_data = get_user_from_token();
    if (!$user_data) {
        http_response_code(401);
        echo json_encode(['message' => 'Unauthorized.']);
        exit();
    }

    $input = json_decode(file_get_contents("php://input"));
    
    if (!isset($input->currentPassword) || !isset($input->newPassword)) {
        http_response_code(400);
        echo json_encode(['message' => 'Current and new password are required.']);
        exit();
    }
    if (strlen($input->newPassword) < 8) {
         http_response_code(400);
        echo json_encode(['message' => 'New password must be at least 8 characters long.']);
        exit();
    }

    $query = 'SELECT password FROM users WHERE id = :id';
    $stmt = $db->prepare($query);
    $stmt->bindParam(':id', $user_data->id);
    $stmt->execute();

    if ($stmt->rowCount() == 1) {
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (password_verify($input->currentPassword, $user['password'])) {
            $newHashedPassword = password_hash($input->newPassword, PASSWORD_DEFAULT);
            $update_query = 'UPDATE users SET password = :password WHERE id = :id';
            $update_stmt = $db->prepare($update_query);
            $update_stmt->bindParam(':password', $newHashedPassword);
            $update_stmt->bindParam(':id', $user_data->id);
            
            if ($update_stmt->execute()) {
                echo json_encode(['message' => 'Password updated successfully.']);
            } else {
                http_response_code(500);
                echo json_encode(['message' => 'Failed to update password.']);
            }
        } else {
            http_response_code(401);
            echo json_encode(['message' => 'Incorrect current password.']);
        }
    } else {
        http_response_code(404);
        echo json_encode(['message' => 'User not found.']);
    }
}
?>