<?php
/**
 * Change Agent Password - API endpoint for store owners to change their agents' passwords
 */

session_start();
require_once '../config.php';
require_once '../app/classes/StoreManager.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Authentication required']);
    exit;
}

$userId = $_SESSION['user_id'];

// Get JSON input
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!$data) {
    echo json_encode(['success' => false, 'message' => 'Invalid request data']);
    exit;
}

// Validate required fields
if (empty($data['agent_id']) || empty($data['new_password'])) {
    echo json_encode(['success' => false, 'message' => 'Agent ID and new password are required']);
    exit;
}

$agentId = intval($data['agent_id']);
$newPassword = $data['new_password'];

if ($agentId <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid agent ID']);
    exit;
}

// Verify user owns a store and change password
$storeManager = new StoreManager($conn);
$result = $storeManager->changeAgentPassword($userId, $agentId, $newPassword);

echo json_encode($result);
?>

