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

function ensure_admin_supplier() {
  if (!has_role(['admin','super_admin'])) {
    json_response(['message' => 'Forbidden'], 403);
  }
}

function generate_supplier_code($mysqli) {
  // Format: SUP-YYYYMM-####
  $prefix = 'SUP-' . date('Ym') . '-';
  $like = $prefix . '%';
  $stmt = $mysqli->prepare("SELECT supplier_code FROM suppliers WHERE supplier_code LIKE ? ORDER BY supplier_code DESC LIMIT 1");
  $stmt->bind_param('s', $like);
  $stmt->execute();
  $res = $stmt->get_result()->fetch_assoc();
  $next = 1;
  if ($res && preg_match('/^(?:SUP-\d{6}-)(\d{4})$/', $res['supplier_code'], $m)) {
    $next = (int)$m[1] + 1;
  }
  return $prefix . str_pad((string)$next, 4, '0', STR_PAD_LEFT);
}

switch ($action) {
  case 'list':
    $res = $mysqli->query('SELECT id, supplier_code, name, contact_person, email, phone, country, is_active FROM suppliers ORDER BY id DESC');
    $data = [];
    while ($row = $res->fetch_assoc()) { $data[] = $row; }
    json_response(['data' => $data]);
    break;

  case 'get':
    $id = (int)($_GET['id'] ?? 0);
    $stmt = $mysqli->prepare('SELECT id, supplier_code, name, contact_person, email, phone, address, country, tax_id, payment_terms, currency, is_active FROM suppliers WHERE id = ?');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    if (!$row) json_response(['message' => 'Not found'], 404);
    json_response(['data' => $row]);
    break;

  case 'create':
    ensure_admin_supplier();
    if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message' => 'Invalid CSRF'], 400);
    $supplier_code = trim($_POST['supplier_code'] ?? '');
    $name = trim($_POST['name'] ?? '');
    $contact_person = trim($_POST['contact_person'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $country = trim($_POST['country'] ?? '');
    $tax_id = trim($_POST['tax_id'] ?? '');
    $payment_terms = trim($_POST['payment_terms'] ?? '');
    $currency = trim($_POST['currency'] ?? '');
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    if (!$name) json_response(['message' => 'Name required'], 400);
    if ($supplier_code === '') {
      $supplier_code = generate_supplier_code($mysqli);
    }
    $stmt = $mysqli->prepare('INSERT INTO suppliers (supplier_code, name, contact_person, email, phone, address, country, tax_id, payment_terms, currency, is_active) VALUES (?,?,?,?,?,?,?,?,?,?,?)');
    $stmt->bind_param('ssssssssssi', $supplier_code, $name, $contact_person, $email, $phone, $address, $country, $tax_id, $payment_terms, $currency, $is_active);
    if (!$stmt->execute()) json_response(['message' => $stmt->error], 500);
    json_response(['message' => 'Created']);
    break;

  case 'update':
    ensure_admin_supplier();
    if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message' => 'Invalid CSRF'], 400);
    $id = (int)($_POST['id'] ?? 0);
    $supplier_code = trim($_POST['supplier_code'] ?? '');
    $name = trim($_POST['name'] ?? '');
    $contact_person = trim($_POST['contact_person'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $country = trim($_POST['country'] ?? '');
    $tax_id = trim($_POST['tax_id'] ?? '');
    $payment_terms = trim($_POST['payment_terms'] ?? '');
    $currency = trim($_POST['currency'] ?? '');
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    if (!$id || !$name) json_response(['message' => 'Missing fields'], 400);
    // Allow supplier_code to be NULL if left blank
    $supplier_code = $supplier_code !== '' ? $supplier_code : null;
    $stmt = $mysqli->prepare('UPDATE suppliers SET supplier_code=?, name=?, contact_person=?, email=?, phone=?, address=?, country=?, tax_id=?, payment_terms=?, currency=?, is_active=? WHERE id=?');
    $stmt->bind_param('ssssssssssii', $supplier_code, $name, $contact_person, $email, $phone, $address, $country, $tax_id, $payment_terms, $currency, $is_active, $id);
    if (!$stmt->execute()) json_response(['message' => $stmt->error], 500);
    json_response(['message' => 'Updated']);
    break;

  case 'delete':
    ensure_admin_supplier();
    if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message' => 'Invalid CSRF'], 400);
    $id = (int)($_POST['id'] ?? 0);
    if (!$id) json_response(['message' => 'Missing id'], 400);
    $stmt = $mysqli->prepare('DELETE FROM suppliers WHERE id = ?');
    $stmt->bind_param('i', $id);
    if (!$stmt->execute()) json_response(['message' => $stmt->error], 500);
    json_response(['message' => 'Deleted']);
    break;

  case 'generate_code':
    ensure_admin_supplier();
    $code = generate_supplier_code($mysqli);
    json_response(['code' => $code]);
    break;

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