<?php
// includes/production_lib.php
// ============================================================
// Helpers para producción por artículo:
// - get_or_create_production_day(): asegura cabecera production_day
// - upsert_production_item(): guarda/actualiza renglón por producto
// - recalc_production_day_totals(): recalcula total_prod_qty
// ============================================================

declare(strict_types=1);

require_once __DIR__ . '/auth.php';

function get_or_create_production_day(PDO $pdo, int $companyId, int $locationId, string $prodDate, int $userId): int {
  // Buscar cabecera del día
  $st = $pdo->prepare("
    SELECT id
    FROM production_day
    WHERE company_id=? AND location_id=? AND prod_date=?
    LIMIT 1
  ");
  $st->execute([$companyId, $locationId, $prodDate]);
  $id = (int)($st->fetchColumn() ?: 0);
  if ($id > 0) return $id;

  // Crear cabecera
  $st = $pdo->prepare("
    INSERT INTO production_day(company_id,location_id,prod_date,created_by,notes,antenna_total_qty,total_prod_qty,diff_qty,warn_flag,locked)
    VALUES(?,?,?,?,NULL,0,0,0,0,0)
  ");
  $st->execute([$companyId, $locationId, $prodDate, $userId]);
  return (int)$pdo->lastInsertId();
}

function recalc_production_day_totals(PDO $pdo, int $productionDayId): void {
  $st = $pdo->prepare("
    UPDATE production_day d
    JOIN (
      SELECT production_day_id,
             SUM(
               t1_ok+t1_m+t1_s+
               t2_ok+t2_m+t2_s+
               t3_ok+t3_m+t3_s
             ) AS tot
      FROM production_day_items
      WHERE production_day_id=?
      GROUP BY production_day_id
    ) x ON x.production_day_id = d.id
    SET d.total_prod_qty = COALESCE(x.tot,0)
    WHERE d.id=?
  ");
  $st->execute([$productionDayId, $productionDayId]);
}

function upsert_production_item(
  PDO $pdo,
  int $productionDayId,
  int $companyId,
  int $locationId,
  string $prodDate,
  int $productId,
  string $field,
  float $value
): void {
  // field permitido (evita inyección)
  $allowed = [
    't1_ok','t1_m','t1_s',
    't2_ok','t2_m','t2_s',
    't3_ok','t3_m','t3_s'
  ];
  if (!in_array($field, $allowed, true)) {
    throw new RuntimeException('Campo inválido');
  }

  // Asegurar fila (si no existe, insert con ceros)
  $st = $pdo->prepare("
    INSERT INTO production_day_items(production_day_id,company_id,location_id,prod_date,product_id)
    VALUES(?,?,?,?,?)
    ON DUPLICATE KEY UPDATE updated_at=NOW()
  ");
  $st->execute([$productionDayId,$companyId,$locationId,$prodDate,$productId]);

  // Update del campo editado
  $sql = "UPDATE production_day_items SET {$field}=? WHERE production_day_id=? AND product_id=? LIMIT 1";
  $st2 = $pdo->prepare($sql);
  $st2->execute([$value, $productionDayId, $productId]);
}