<?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('insurer.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, 'insurer', $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 short_name LIKE :q2 OR email LIKE :q3)';
        $params['q1'] = $q; $params['q2'] = $q; $params['q3'] = $q;
    }

    $stmt = $pdo->prepare("SELECT * FROM insurers 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('insurer.create') && !can('insurer.edit')) {
        respond(['status' => 'error', 'message' => 'Unauthorized']);
    }

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

    $data = [
        'name' => $name,
        'short_name' => trim($_POST['short_name'] ?? ''),
        'address' => trim($_POST['address'] ?? ''),
        'phone' => trim($_POST['phone'] ?? ''),
        'email' => trim($_POST['email'] ?? ''),
        'website' => trim($_POST['website'] ?? ''),
        'contact_person' => trim($_POST['contact_person'] ?? ''),
        'contact_phone' => trim($_POST['contact_phone'] ?? ''),
        '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 insurers SET {$sets} WHERE id = :id")->execute($data);
        doAudit($pdo, 'update', "Insurer #{$id} updated", $id);
        respond(['status' => 'success', 'message' => 'Insurer updated']);
    } else {
        $cols = implode(', ', array_keys($data));
        $vals = ':' . implode(', :', array_keys($data));
        $pdo->prepare("INSERT INTO insurers ({$cols}) VALUES ({$vals})")->execute($data);
        $newId = (int)$pdo->lastInsertId();
        doAudit($pdo, 'create', "Insurer #{$newId} created", $newId);
        respond(['status' => 'success', 'message' => 'Insurer created', 'id' => $newId]);
    }
}

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