<?php
// api/movimiento_list.php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }
session_start();
require_once __DIR__ . '/../conex.php';
mysqli_set_charset($conn,'utf8mb4');

$search = trim((string)($_GET['search'] ?? ''));

$sql = "SELECT m.id_movimiento, m.fecha, m.tipo, 
               bo.nombre AS bodega_origen, bd.nombre AS bodega_destino,
               m.motivo, m.ref_tipo, m.ref_id,
               (SELECT COUNT(*) FROM tb_inv_movimiento_det d WHERE d.id_movimiento=m.id_movimiento) AS items
        FROM tb_inv_movimiento m
        LEFT JOIN tb_inv_bodega bo ON bo.id_bodega = m.id_bodega_origen
        LEFT JOIN tb_inv_bodega bd ON bd.id_bodega = m.id_bodega_destino
        WHERE 1=1";
$params=[];$types='';

if ($search!==''){
  $sql.=" AND (m.tipo LIKE CONCAT('%',?,'%')
           OR IFNULL(bo.nombre,'') LIKE CONCAT('%',?,'%')
           OR IFNULL(bd.nombre,'') LIKE CONCAT('%',?,'%')
           OR IFNULL(m.motivo,'') LIKE CONCAT('%',?,'%')
           OR IFNULL(m.ref_tipo,'') LIKE CONCAT('%',?,'%')
           OR IFNULL(m.ref_id,'') LIKE CONCAT('%',?,'%'))";
  $params=[$search,$search,$search,$search,$search,$search];
  $types='ssssss';
}
$sql.=" ORDER BY m.fecha DESC, m.id_movimiento DESC";

$stmt = mysqli_prepare($conn,$sql);
if ($params) mysqli_stmt_bind_param($stmt,$types,...$params);
mysqli_stmt_execute($stmt);
$res = mysqli_stmt_get_result($stmt);

$data=[];
while($row=mysqli_fetch_assoc($res)) $data[]=$row;

echo json_encode(['success'=>true,'data'=>$data]);
