<?php
declare(strict_types=1);

require_once __DIR__ . '/../../../app/Config/config.php';
require_once __DIR__ . '/../../../app/Config/functions.php';
require_once __DIR__ . '/../../../app/Models/Vendor.php';

require_login();

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

try {
    $id = (int)($_POST['id'] ?? 0);

    if ($id <= 0) {
        throw new Exception('Invalid vendor ID.');
    }

    // Optional: check for linked bills before deleting
    $pdo = Database::getConnection();
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM ap_bills WHERE vendor_id=?");
    $stmt->execute([$id]);
    $linked = (int)$stmt->fetchColumn();

    if ($linked > 0) {
        throw new Exception('Vendor cannot be deleted because linked bills exist.');
    }

    $model = new Vendor();
    $success = $model->delete($id);

    echo json_encode([
        'status'  => $success ? 'success' : 'error',
        'message' => $success ? 'Vendor deleted successfully.' : 'Failed to delete vendor.'
    ]);
} catch (Throwable $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
