<?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';

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

requireApiLogin();
enforceCsrfForUnsafeRequest();

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

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

try {
    switch ($action) {
        case 'list': handleList($pdo); break;
        case 'save': handleSave($pdo); break;
        case 'delete': handleDelete($pdo); break;
        case 'categories': handleCategories($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, 'part_catalog', $recordId ?? 0, $description, null, null);
}

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

    if (!empty($_GET['category_id'])) {
        $where[] = 'c.category_id = :category_id';
        $params['category_id'] = (int)$_GET['category_id'];
    }
    if (!empty($_GET['search'])) {
        $q = '%' . $_GET['search'] . '%';
        $where[] = '(c.name LIKE :q1 OR c.part_number LIKE :q2)';
        $params['q1'] = $q; $params['q2'] = $q;
    }
    if (!empty($_GET['active_only'])) {
        $where[] = 'c.is_active = 1';
    }

    $stmt = $pdo->prepare("
        SELECT c.*, pc.name AS category_name
        FROM part_catalog c
        LEFT JOIN part_categories pc ON pc.id = c.category_id
        WHERE " . implode(' AND ', $where) . "
        ORDER BY c.name ASC
    ");
    $stmt->execute($params);
    respond(['status' => 'success', 'data' => $stmt->fetchAll()]);
}

function handleCategories(PDO $pdo): void
{
    $stmt = $pdo->query("SELECT * FROM part_categories ORDER BY name ASC");
    respond(['status' => 'success', 'data' => $stmt->fetchAll()]);
}

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

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

    $data = [
        'name' => $name,
        'part_number' => trim($_POST['part_number'] ?? ''),
        'category_id' => !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null,
        'default_unit_cost' => !empty($_POST['default_unit_cost']) ? (float)$_POST['default_unit_cost'] : null,
        'default_reorder_level' => !empty($_POST['default_reorder_level']) ? (float)$_POST['default_reorder_level'] : null,
        'unit_of_measure' => trim($_POST['unit_of_measure'] ?? ''),
    ];

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

function handleDelete(PDO $pdo): void
{
    if (!isAdmin() && !can('part_catalog.delete')) {
        respond(['status' => 'error', 'message' => 'Unauthorized']);
    }
    $id = (int)($_POST['id'] ?? 0);
    if ($id <= 0) respond(['status' => 'error', 'message' => 'Invalid ID']);
    $pdo->prepare("UPDATE part_catalog SET is_active = 0 WHERE id = :id")->execute(['id' => $id]);
    doAudit($pdo, 'delete', "Catalog item #{$id} deactivated", $id);
    respond(['status' => 'success', 'message' => 'Catalog item deactivated']);
}
