<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../config/database.php';

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

if ($action === 'list') {
    $sql = "SELECT id AS __backendId, supplier_name, address, email, contact_no, contact_person, item_category, created_at FROM suppliers ORDER BY id DESC";
    $result = $mysqli->query($sql);
    $data = [];
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
    }
    echo json_encode($data);
    exit;
}

if ($action === 'create') {
    $supplier_name = $_POST['supplier_name'] ?? '';
    $address = $_POST['address'] ?? '';
    $email = $_POST['email'] ?? '';
    $contact_no = $_POST['contact_no'] ?? '';
    $contact_person = $_POST['contact_person'] ?? '';
    $item_category = $_POST['item_category'] ?? '';

    $stmt = $mysqli->prepare("INSERT INTO suppliers (supplier_name, address, email, contact_no, contact_person, item_category, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");
    if ($stmt) {
        $stmt->bind_param("ssssss", $supplier_name, $address, $email, $contact_no, $contact_person, $item_category);
        $ok = $stmt->execute();
        $response = ['success' => $ok];
        if ($ok) {
            $response['insert_id'] = $stmt->insert_id;
        }
        echo json_encode($response);
    } else {
        echo json_encode(['success' => false, 'error' => 'Database prepare failed']);
    }
    exit;
}

if ($action === 'delete') {
    $id = $_GET['id'] ?? $_POST['id'] ?? null;
    if (!$id) {
        echo json_encode(['success' => false, 'error' => 'Missing supplier id']);
        exit;
    }

    $stmt = $mysqli->prepare("DELETE FROM suppliers WHERE id = ?");
    if ($stmt) {
        $stmt->bind_param("i", $id);
        $ok = $stmt->execute();
        echo json_encode(['success' => $ok]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Database prepare failed']);
    }
    exit;
}

echo json_encode(['success' => false, 'error' => 'Invalid action']);
