<?php
session_start();

require(realpath(__DIR__ . '/../../../services/Model.php'));
$obj = new Model();

$userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : NULL;

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['id'], $_GET['sale'], $_GET['batch'])) {
    $sale_id = (int)($_GET['sale'] ?? 0);
    $product_id = (int)($_GET['id'] ?? 0);
    $batch_id = trim($_GET['batch'] ?? '');

    if ($sale_id <= 0 || $product_id <= 0 || $batch_id === '') {
        echo json_encode(['success' => false, 'status' => 'Invalid sale request']);
        exit;
    }

    $sale = $obj->rawSqlSingle("SELECT * FROM sales WHERE sale_id = '$sale_id' AND deleted_at IS NULL");
    if (!$sale) {
        echo json_encode(['success' => false, 'status' => 'Sale not found']);
        exit;
    }

    $selectedModelIds = json_decode($sale['model_id'], true);
    if (!is_array($selectedModelIds)) {
        $selectedModelIds = [];
    }

    $selectedModelIds = array_values(array_unique(array_filter(array_map('intval', $selectedModelIds))));
    $saleModels = [];

    foreach ($selectedModelIds as $modelId) {
        $model = $obj->rawSqlSingle("
            SELECT *
            FROM product_model
            WHERE deleted_at IS NULL
              AND id = '$modelId'
              AND product_id = '$product_id'
              AND batch_id = '$batch_id'
        ");

        if ($model) {
            $saleModels[] = $model;
        }
    }

    $excludeClause = '';
    if (!empty($selectedModelIds)) {
        $excludeClause = ' AND id NOT IN (' . implode(',', $selectedModelIds) . ')';
    }

    $unsoldModels = $obj->rawSql("
        SELECT *
        FROM product_model
        WHERE deleted_at IS NULL
          AND sold = 0
          AND returned = 0
          AND product_id = '$product_id'
          AND batch_id = '$batch_id'
          $excludeClause
    ");

    foreach ($unsoldModels as $unsoldModel) {
        $saleModels[] = $unsoldModel;
    }

    echo json_encode(['success' => true, 'modelIds' => $saleModels]);
    exit;
}
