<?php
declare(strict_types=1);
require_once '../config/database.php';
require_once '../app/helpers/rbac.php';
require_once '../app/helpers/audit.php';
require_once '../app/helpers/api_security.php';
require_once '../app/helpers/soft_delete.php';

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

requireApiLogin();
enforceCsrfForUnsafeRequest();

$action = $_GET['action'] ?? '';

if (!isAdmin() && !can('supplier.view')) {
    respond(['status' => 'error', 'message' => 'Unauthorized']);
}

try {
    switch ($action) {
        case 'list': handleList($pdo); break;
        case 'save': handleSave($pdo); break;
        case 'delete': handleDelete($pdo); break;
        default: respond(['status' => 'error', 'message' => 'Unknown action']);
    }
} catch (Exception $e) {
    respond(['status' => 'error', 'message' => $e->getMessage()]);
}

function respond(array $payload): void { apiRespond($payload); }

function doAudit(PDO $pdo, string $action, string $description, ?int $recordId = null): void {
    audit($pdo, (int)($_SESSION['user_id'] ?? 0), $action, 'supplier', $recordId ?? 0, $description, null, null);
}

function handleList(PDO $pdo): void
{
    $where = ['deleted_at IS NULL'];
    $params = [];

    if (!empty($_GET['status'])) {
        $where[] = 'status = :status';
        $params['status'] = $_GET['status'];
    }
    if (!empty($_GET['search'])) {
        $q = '%' . $_GET['search'] . '%';
        $where[] = '(name LIKE :q1 OR email LIKE :q2 OR phone LIKE :q3 OR contact_person LIKE :q4)';
        $params['q1'] = $q; $params['q2'] = $q; $params['q3'] = $q; $params['q4'] = $q;
    }

    $stmt = $pdo->prepare("SELECT * FROM suppliers WHERE " . implode(' AND ', $where) . " ORDER BY name ASC");
    $stmt->execute($params);
    respond(['status' => 'success', 'data' => $stmt->fetchAll()]);
}

function handleSave(PDO $pdo): void
{
    if (!isAdmin() && !can('supplier.create') && !can('supplier.edit')) {
        respond(['status' => 'error', 'message' => 'Unauthorized']);
    }

    $id = (int)($_POST['id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    if (!$name) respond(['status' => 'error', 'message' => 'Supplier name is required']);

    $data = [
        'name' => $name,
        'contact_person' => trim($_POST['contact_person'] ?? ''),
        'phone' => trim($_POST['phone'] ?? ''),
        'email' => trim($_POST['email'] ?? ''),
        'address' => trim($_POST['address'] ?? ''),
        'status' => $_POST['status'] ?? 'active',
    ];

    if ($id > 0) {
        $data['id'] = $id;
        $sets = implode(', ', array_map(function ($c) { return "{$c} = :{$c}"; }, array_keys($data)));
        $pdo->prepare("UPDATE suppliers SET {$sets} WHERE id = :id")->execute($data);
        doAudit($pdo, 'update', "Supplier #{$id} updated", $id);
        respond(['status' => 'success', 'message' => 'Supplier updated']);
    } else {
        $cols = implode(', ', array_keys($data));
        $vals = ':' . implode(', :', array_keys($data));
        $pdo->prepare("INSERT INTO suppliers ({$cols}) VALUES ({$vals})")->execute($data);
        $newId = (int)$pdo->lastInsertId();
        doAudit($pdo, 'create', "Supplier #{$newId} created", $newId);
        respond(['status' => 'success', 'message' => 'Supplier created', 'id' => $newId]);
    }
}

function handleDelete(PDO $pdo): void
{
    if (!isAdmin() && !can('supplier.delete')) {
        respond(['status' => 'error', 'message' => 'Unauthorized']);
    }
    $id = (int)($_POST['id'] ?? 0);
    if ($id <= 0) respond(['status' => 'error', 'message' => 'Invalid ID']);
    softDelete($pdo, 'suppliers', $id);
    doAudit($pdo, 'delete', "Supplier #{$id} deleted", $id);
    respond(['status' => 'success', 'message' => 'Supplier deleted']);
}
