<?php
// /api/customers.php
require_once __DIR__ . '/middleware.php';
require_once __DIR__ . '/../Controllers/CustomerController.php';

$action = $_GET['action'] ?? $_POST['action'] ?? 'list';
$input = json_decode(file_get_contents('php://input'), true) ?: $_POST;

$ctrl = new Controllers\CustomerController();

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

switch($action) {
  case 'get':
    $id = $input['id'] ?? $_GET['id'] ?? null;
    if (!$id) { echo json_encode(['status'=>0,'error'=>'missing_id']); exit; }
    echo json_encode($ctrl->get($id));
    break;

  case 'create':
    $user = api_authenticate_or_die();
    echo json_encode($ctrl->create($input, $user));
    break;

  case 'update':
    $user = api_authenticate_or_die();
    $id = $input['id'] ?? null;
    if (!$id) { echo json_encode(['status'=>0,'error'=>'missing_id']); exit; }
    echo json_encode($ctrl->update($id, $input, $user));
    break;

  case 'delete':
    $user = api_authenticate_or_die();
    $id = $input['id'] ?? null;
    if (!$id) { echo json_encode(['status'=>0,'error'=>'missing_id']); exit; }
    echo json_encode($ctrl->delete($id, $user));
    break;

  case 'list':
  default:
    // list supports pagination: page, q, per_page
    $page = intval($_GET['page'] ?? 1);
    $q = $_GET['q'] ?? '';
    $per = intval($_GET['per'] ?? 25);
    echo json_encode($ctrl->list($page, $per, $q));
    break;
}
?>