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

$pdo = db();
$method = $_SERVER['REQUEST_METHOD'];
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : ($method === 'GET' ? 'list' : '');

function json_out($data, $code = 200) {
  http_response_code($code);
  echo json_encode($data);
  exit;
}

try {
  if ($method === 'GET' && $action === 'list') {
    $stmt = $pdo->query("
      SELECT s.*, sh.shipper_name, i.invoice_no
      FROM shipments s
      LEFT JOIN shippers sh ON s.shipper_id = sh.id
      LEFT JOIN invoices i ON s.invoice_id = i.id
      ORDER BY s.id DESC
    ");
    json_out(['ok' => true, 'data' => $stmt->fetchAll()]);
  }

  if ($method === 'GET' && $action === 'get') {
    $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
    if (!$id) json_out(['ok' => false, 'error' => 'id required'], 400);
    $stmt = $pdo->prepare("
      SELECT s.*, sh.shipper_name, i.invoice_no
      FROM shipments s
      LEFT JOIN shippers sh ON s.shipper_id = sh.id
      LEFT JOIN invoices i ON s.invoice_id = i.id
      WHERE s.id = ?
    ");
    $stmt->execute([$id]);
    $row = $stmt->fetch();
    if (!$row) json_out(['ok' => false, 'error' => 'Not found'], 404);
    json_out(['ok' => true, 'data' => $row]);
  }

  if ($method === 'GET' && $action === 'next_id') {
    $nextId = 'SHP-' . time();
    json_out(['ok' => true, 'shipment_id' => $nextId]);
  }

  if ($method === 'POST' && ($action === '' || $action === 'create')) {
    if (!empty($_POST)) {
      $data = $_POST;
    } else {
      $data = json_decode(file_get_contents('php://input'), true);
    }

    if (!$data) json_out(['ok' => false, 'error' => 'invalid data'], 400);

    $shipment_id = isset($data['shipment_id']) ? (string)$data['shipment_id'] : '';
    $enter_date = isset($data['enter_date']) ? (string)$data['enter_date'] : '';
    $arrival_date = isset($data['arrival_date']) ? (string)$data['arrival_date'] : '';
    $container_no = isset($data['container_no']) ? (string)$data['container_no'] : '';
    $container_weight = isset($data['container_weight']) ? (float)$data['container_weight'] : 0.0;
    $shipper_id = isset($data['shipper_id']) ? (int)$data['shipper_id'] : 0;
    $mode = isset($data['mode']) ? (string)$data['mode'] : '';
    $pcs_ctns_pallets = isset($data['pcs_ctns_pallets']) ? (int)$data['pcs_ctns_pallets'] : 0;
    $via = isset($data['via']) ? (string)$data['via'] : '';
    $invoice_id = isset($data['invoice_id']) ? (int)$data['invoice_id'] : 0;

    if (!$shipment_id || !$enter_date || !$arrival_date || !$container_no || $container_weight <= 0 || !$shipper_id || !$mode || $pcs_ctns_pallets <= 0 || !$via || !$invoice_id) {
      json_out(['ok' => false, 'error' => 'missing required fields'], 400);
    }

    $stmt = $pdo->prepare("
      INSERT INTO shipments
      (shipment_id, enter_date, arrival_date, container_no, container_weight, shipper_id, mode, pcs_ctns_pallets, via, invoice_id)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([
      $shipment_id, $enter_date, $arrival_date, $container_no, $container_weight, $shipper_id, $mode, $pcs_ctns_pallets, $via, $invoice_id
    ]);
    json_out(['ok' => true, 'id' => (int)$pdo->lastInsertId()]);
  }

  if ($method === 'POST' && $action === 'update') {
    if (!empty($_POST)) {
      $data = $_POST;
    } else {
      $data = json_decode(file_get_contents('php://input'), true);
    }
    if (!$data) json_out(['ok' => false, 'error' => 'invalid data'], 400);
    $id = isset($data['id']) ? (int)$data['id'] : 0;
    if (!$id) json_out(['ok' => false, 'error' => 'id required'], 400);
    $shipment_id = isset($data['shipment_id']) ? (string)$data['shipment_id'] : '';
    $enter_date = isset($data['enter_date']) ? (string)$data['enter_date'] : '';
    $arrival_date = isset($data['arrival_date']) ? (string)$data['arrival_date'] : '';
    $container_no = isset($data['container_no']) ? (string)$data['container_no'] : '';
    $container_weight = isset($data['container_weight']) ? (float)$data['container_weight'] : 0.0;
    $shipper_id = isset($data['shipper_id']) ? (int)$data['shipper_id'] : 0;
    $mode = isset($data['mode']) ? (string)$data['mode'] : '';
    $pcs_ctns_pallets = isset($data['pcs_ctns_pallets']) ? (int)$data['pcs_ctns_pallets'] : 0;
    $via = isset($data['via']) ? (string)$data['via'] : '';
    $invoice_id = isset($data['invoice_id']) ? (int)$data['invoice_id'] : 0;
    if (!$shipment_id || !$enter_date || !$arrival_date || !$container_no || $container_weight <= 0 || !$shipper_id || !$mode || $pcs_ctns_pallets <= 0 || !$via || !$invoice_id) {
      json_out(['ok' => false, 'error' => 'missing required fields'], 400);
    }
    $stmt = $pdo->prepare("
      UPDATE shipments
      SET shipment_id=?, enter_date=?, arrival_date=?, container_no=?, container_weight=?, shipper_id=?, mode=?, pcs_ctns_pallets=?, via=?, invoice_id=?
      WHERE id=?
    ");
    $stmt->execute([
      $shipment_id, $enter_date, $arrival_date, $container_no, $container_weight, $shipper_id, $mode, $pcs_ctns_pallets, $via, $invoice_id, $id
    ]);
    json_out(['ok' => true, 'id' => $id]);
  }

  if ($method === 'POST' && $action === 'delete') {
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    if (!$id) json_out(['ok' => false, 'error' => 'id required'], 400);
    $stmt = $pdo->prepare("DELETE FROM shipments WHERE id = ?");
    $stmt->execute([$id]);
    json_out(['ok' => true]);
  }

  json_out(['ok' => false, 'error' => 'invalid request'], 400);
} catch (Throwable $e) {
  json_out(['ok' => false, 'error' => $e->getMessage()], 500);
}
