<?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/Supplier.php';

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

$supplier = new Supplier();

if ($method === 'GET' && $action === 'get_all') {
    $suppliers = $supplier->getAllSuppliers();
    echo json_encode($suppliers);
} else if ($method === 'GET' && $action === 'get') {
    $id = isset($_GET['id']) ? $_GET['id'] : '';
    $supp = $supplier->getSupplier($id);
    
    if ($supp) {
        echo json_encode($supp);
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'Supplier not found']);
    }
} else if ($method === 'POST' && $action === 'create') {
    $data = json_decode(file_get_contents("php://input"), true);
    $result = $supplier->createSupplier($data);
    echo json_encode($result);
} else if ($method === 'POST' && $action === 'create_payment') {
    $data = json_decode(file_get_contents("php://input"), true);
    
    if (!isset($data['id'])) {
        $data['id'] = 'SP-' . time();
    }
    
    if ($supplier->createPayment($data)) {
        echo json_encode(['success' => true, 'message' => 'Payment recorded']);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to record payment']);
    }
} else if ($method === 'GET' && $action === 'payments') {
    $supplierId = isset($_GET['supplier_id']) ? $_GET['supplier_id'] : '';
    $payments = $supplier->getSupplierPayments($supplierId);
    echo json_encode($payments);
} else if ($method === 'GET' && $action === 'balance') {
    $supplierId = isset($_GET['supplier_id']) ? $_GET['supplier_id'] : '';
    $balance = $supplier->getSupplierBalance($supplierId);
    echo json_encode($balance);
} else {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid action']);
}
?>
