<?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_import(){ if (!has_role(['admin','super_admin'])) json_response(['message'=>'Forbidden'], 403); }

function save_attach() {
  if (!isset($_FILES['attachment']) || !is_uploaded_file($_FILES['attachment']['tmp_name'])) return null;
  $dir = __DIR__ . '/../uploads/imports';
  if (!is_dir($dir)) @mkdir($dir, 0775, true);
  $name = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/','_', $_FILES['attachment']['name']);
  $target = $dir . '/' . $name;
  if (!move_uploaded_file($_FILES['attachment']['tmp_name'], $target)) return null;
  return 'uploads/imports/' . $name;
}

switch ($action) {
  case 'list':
    $q = trim($_GET['q'] ?? '');
    $po_id = (int)($_GET['po_id'] ?? 0);
    $from = $_GET['from'] ?? '';
    $to = $_GET['to'] ?? '';
    $where=[];$types='';$params=[];
    if ($q !== '') { $where[] = '(i.reference_no LIKE CONCAT("%", ?, "%") OR p.order_no LIKE CONCAT("%", ?, "%"))'; $types.='ss'; $params[]=$q; $params[]=$q; }
    if ($po_id) { $where[] = 'i.po_id = ?'; $types.='i'; $params[]=$po_id; }
    if ($from !== '') { $where[] = 'i.import_date >= ?'; $types.='s'; $params[]=$from; }
    if ($to !== '') { $where[] = 'i.import_date <= ?'; $types.='s'; $params[]=$to; }
    $sql = 'SELECT i.id, i.import_date, i.reference_no, i.transporter, i.vehicle_no, i.warehouse, i.notes, i.attachment_path, p.order_no FROM imports i LEFT JOIN purchase_orders p ON p.id=i.po_id';
    if ($where) $sql .= ' WHERE ' . implode(' AND ', $where);
    $sql .= ' ORDER BY i.id DESC';
    if ($where) { $stmt=$mysqli->prepare($sql); $stmt->bind_param($types, ...$params); $stmt->execute(); $res=$stmt->get_result(); }
    else { $res=$mysqli->query($sql); }
    $data=[]; while($r=$res->fetch_assoc()){ $data[]=$r; }
    json_response(['data'=>$data]);
    break;

  case 'get':
    $id=(int)($_GET['id'] ?? 0); if(!$id) json_response(['message'=>'Missing id'],400);
    $stmt=$mysqli->prepare('SELECT * FROM imports WHERE id=?');
    $stmt->bind_param('i',$id); $stmt->execute(); $imp=$stmt->get_result()->fetch_assoc();
    if(!$imp) json_response(['message'=>'Not found'],404);
    $it=$mysqli->prepare('SELECT ii.id, ii.po_item_id, ii.material_id, ii.qty_received, ii.batch_no, ii.remarks, i.description, i.quantity AS po_qty FROM import_items ii LEFT JOIN purchase_order_items i ON i.id=ii.po_item_id WHERE ii.import_id=?');
    $it->bind_param('i',$id); $it->execute(); $items=[]; $r=$it->get_result(); while($row=$r->fetch_assoc()){ $items[]=$row; }
    $imp['items']=$items;
    json_response(['data'=>$imp]);
    break;

  case 'create':
    ensure_admin_import(); if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'],400);
    $po_id=(int)($_POST['po_id'] ?? 0);
    $import_date=$_POST['import_date'] ?? '';
    $reference_no=trim($_POST['reference_no'] ?? '');
    $transporter=trim($_POST['transporter'] ?? '');
    $vehicle_no=trim($_POST['vehicle_no'] ?? '');
    $warehouse=trim($_POST['warehouse'] ?? '');
    $notes=trim($_POST['notes'] ?? '');
    $items_json=$_POST['items_json'] ?? '[]';
    $items=json_decode($items_json,true); if(!is_array($items)) $items=[];
    if(!$po_id || !$import_date) json_response(['message'=>'Missing fields'],400);
    // only allow received POs
    $st=$mysqli->prepare('SELECT status FROM purchase_orders WHERE id=?');
    $st->bind_param('i',$po_id); $st->execute(); $row=$st->get_result()->fetch_assoc();
    if(!$row || strtolower($row['status'])!=='received') json_response(['message'=>'PO is not received'],400);
    $attachment=save_attach();
    $ins=$mysqli->prepare('INSERT INTO imports (po_id, import_date, reference_no, transporter, vehicle_no, warehouse, notes, attachment_path) VALUES (?,?,?,?,?,?,?,?)');
    $ins->bind_param('isssssss',$po_id,$import_date,$reference_no,$transporter,$vehicle_no,$warehouse,$notes,$attachment);
    if(!$ins->execute()) json_response(['message'=>$ins->error],500);
    $imp_id=$ins->insert_id;
    if(!empty($items)){
      $pi=$mysqli->prepare('INSERT INTO import_items (import_id, po_item_id, material_id, qty_received, batch_no, remarks) VALUES (?,?,?,?,?,?)');
      foreach($items as $ix){
        $po_item_id=(int)($ix['po_item_id'] ?? 0);
        $material_id=!empty($ix['material_id'])?(int)$ix['material_id']:null;
        $qty=(float)($ix['qty_received'] ?? 0);
        $batch=trim($ix['batch_no'] ?? '');
        $rem=trim($ix['remarks'] ?? '');
        if($po_item_id && $qty>0){
          $pi->bind_param('iiidss',$imp_id,$po_item_id,$material_id,$qty,$batch,$rem);
          if(!$pi->execute()) json_response(['message'=>$pi->error],500);
        }
      }
    }
    json_response(['message'=>'Created']);
    break;

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

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