<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_login();
header('Content-Type: application/json');

$mysqli = db();
$action = $_GET['action'] ?? $_POST['action'] ?? 'list';

// Ensure vendors table exists
$mysqli->query("CREATE TABLE IF NOT EXISTS vendors (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(150) NOT NULL,
    category VARCHAR(100) DEFAULT NULL,
    phone VARCHAR(50) DEFAULT NULL,
    email VARCHAR(150) DEFAULT NULL,
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB");

// Seed common utility vendors if empty
$cnt = $mysqli->query("SELECT COUNT(*) c FROM vendors")->fetch_assoc()['c'];
if ($cnt == 0) {
    $seeds = [
        ['Dialog Axiata',     'Telecom'],
        ['Mobitel',           'Telecom'],
        ['Airtel Lanka',      'Telecom'],
        ['CEB (Ceylon Electricity Board)', 'Utility'],
        ['LECO',              'Utility'],
        ['National Water Supply', 'Utility'],
        ['SLT',               'Telecom'],
        ['Hutch',             'Telecom'],
    ];
    $ins = $mysqli->prepare("INSERT INTO vendors (name, category) VALUES (?, ?)");
    foreach ($seeds as [$name, $cat]) {
        $ins->bind_param('ss', $name, $cat);
        $ins->execute();
    }
    $ins->close();
}

switch ($action) {
    case 'list':
        $res = $mysqli->query("SELECT id, name, category, phone, email, is_active FROM vendors WHERE is_active=1 ORDER BY category, name");
        $data = [];
        while ($row = $res->fetch_assoc()) $data[] = $row;
        json_response(['data' => $data]);
        break;

    case 'list_all':
        if (!has_role(['admin','super_admin'])) json_response(['message'=>'Access denied'],403);
        $res = $mysqli->query("SELECT id, name, category, phone, email, is_active FROM vendors ORDER BY category, name");
        $data = [];
        while ($row = $res->fetch_assoc()) $data[] = $row;
        json_response(['data' => $data]);
        break;

    case 'create':
        if (!has_role(['admin','super_admin'])) json_response(['message'=>'Access denied'],403);
        if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'],400);
        $name  = trim($_POST['name'] ?? '');
        $cat   = trim($_POST['category'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $email = trim($_POST['email'] ?? '');
        if ($name === '') json_response(['message'=>'Name is required'],400);
        $stmt = $mysqli->prepare("INSERT INTO vendors (name, category, phone, email) VALUES (?,?,?,?)");
        $stmt->bind_param('ssss', $name, $cat, $phone, $email);
        if (!$stmt->execute()) json_response(['message'=>'DB error: '.$stmt->error],500);
        json_response(['success'=>true, 'id'=>$mysqli->insert_id, 'message'=>'Vendor created']);
        break;

    case 'update':
        if (!has_role(['admin','super_admin'])) json_response(['message'=>'Access denied'],403);
        if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'],400);
        $id    = (int)($_POST['id'] ?? 0);
        $name  = trim($_POST['name'] ?? '');
        $cat   = trim($_POST['category'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $active= isset($_POST['is_active']) ? (int)$_POST['is_active'] : 1;
        if (!$id || $name==='') json_response(['message'=>'ID and name required'],400);
        $stmt = $mysqli->prepare("UPDATE vendors SET name=?, category=?, phone=?, email=?, is_active=? WHERE id=?");
        $stmt->bind_param('ssssii', $name, $cat, $phone, $email, $active, $id);
        if (!$stmt->execute()) json_response(['message'=>'Update failed: '.$stmt->error],500);
        json_response(['success'=>true, 'message'=>'Updated']);
        break;

    case 'delete':
        if (!has_role(['admin','super_admin'])) json_response(['message'=>'Access denied'],403);
        if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'],400);
        $id = (int)($_POST['id'] ?? 0);
        if (!$id) json_response(['message'=>'ID required'],400);
        $stmt = $mysqli->prepare("DELETE FROM vendors WHERE id=?");
        $stmt->bind_param('i', $id);
        if (!$stmt->execute()) json_response(['message'=>'Delete failed'],500);
        json_response(['success'=>true, 'message'=>'Deleted']);
        break;

    default:
        json_response(['message'=>'Unknown action'],400);
}
