<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Content-Type: application/json; charset=UTF-8");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once __DIR__ . '/../config/Database.php';
require_once __DIR__ . '/../models/Customer.php';

$method = $_SERVER['REQUEST_METHOD'];
$action = isset($_GET['action']) ? $_GET['action'] : '';

$customer = new Customer();

if ($method === 'GET' && $action === 'get_all') {
    $customers = $customer->getAllCustomers();
    echo json_encode($customers);
} else if ($method === 'GET' && $action === 'get') {
    $id = isset($_GET['id']) ? $_GET['id'] : '';
    $cust = $customer->getCustomer($id);
    
    if ($cust) {
        echo json_encode($cust);
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'Customer not found']);
    }
} else if ($method === 'GET' && $action === 'search') {
    $term = isset($_GET['term']) ? $_GET['term'] : '';
    $results = $customer->searchCustomers($term);
    echo json_encode($results);
} else if ($method === 'GET' && $action === 'upcoming_birthdays') {
    $days = isset($_GET['days']) ? $_GET['days'] : 3;
    $birthdays = $customer->getUpcomingBirthdays($days);
    echo json_encode($birthdays);
} else if ($method === 'GET' && $action === 'stats') {
    $id = isset($_GET['id']) ? $_GET['id'] : '';
    $stats = $customer->getCustomerStats($id);
    echo json_encode($stats);
} else if ($method === 'POST' && $action === 'create') {
    $data = json_decode(file_get_contents("php://input"), true);
    $result = $customer->createCustomer($data);
    echo json_encode($result);
} else if ($method === 'PUT' && $action === 'update') {
    $id = isset($_GET['id']) ? $_GET['id'] : '';
    $data = json_decode(file_get_contents("php://input"), true);
    
    if ($customer->updateCustomer($id, $data)) {
        echo json_encode(['success' => true, 'message' => 'Customer updated']);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to update customer']);
    }
} else {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid action']);
}
?>
