<?php
// referencias_laborales/listar.php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Content-Type: application/json; charset=utf-8");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
  http_response_code(200);
  exit;
}

require_once(__DIR__ . '/../config.php'); // $mysqli

$ID_ESTUDIO = isset($_GET['ID_ESTUDIO']) && $_GET['ID_ESTUDIO'] !== '' ? (int)$_GET['ID_ESTUDIO'] : null;
$ID_CANDIDATO_EMPRESA = isset($_GET['ID_CANDIDATO_EMPRESA']) && $_GET['ID_CANDIDATO_EMPRESA'] !== '' ? (int)$_GET['ID_CANDIDATO_EMPRESA'] : null;

if (!$ID_ESTUDIO && !$ID_CANDIDATO_EMPRESA) {
  http_response_code(400);
  echo json_encode([
    "success" => false,
    "message" => "Debes enviar ID_ESTUDIO o ID_CANDIDATO_EMPRESA por GET."
  ]);
  exit;
}

$where = "ESTADO_REGISTRO = 1";
$params = [];
$types = "";

if ($ID_ESTUDIO) {
  $where .= " AND ID_ESTUDIO = ?";
  $params[] = $ID_ESTUDIO;
  $types .= "i";
}

if ($ID_CANDIDATO_EMPRESA) {
  $where .= " AND ID_CANDIDATO_EMPRESA = ?";
  $params[] = $ID_CANDIDATO_EMPRESA;
  $types .= "i";
}

$sql = "SELECT *
        FROM REFERENCIAS_LABORALES
        WHERE $where
        ORDER BY ID_REFERENCIA_LABORAL DESC";

$stmt = $mysqli->prepare($sql);

if ($stmt === false) {
  http_response_code(500);
  echo json_encode(["success" => false, "message" => "Error prepare: " . $mysqli->error]);
  exit;
}

if (!empty($params)) {
  $stmt->bind_param($types, ...$params);
}

if (!$stmt->execute()) {
  http_response_code(500);
  echo json_encode(["success" => false, "message" => "Error execute: " . $stmt->error]);
  exit;
}

$res = $stmt->get_result();
$rows = [];
while ($r = $res->fetch_assoc()) $rows[] = $r;

echo json_encode([
  "success" => true,
  "total" => count($rows),
  "data" => $rows
]);

$stmt->close();
$mysqli->close();
