<?php
/**
 * File: api/karigar/get_wastage_settings.php
 * Purpose: Item-type wise wastage % settings + current gold rate
 * Method : GET
 * Output : { success, data: { items: [...], gold_rates: {...} } }
 * Date   : 2026-05-27
 */

ini_set('display_errors', 0);
error_reporting(E_ALL);

header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../../config/session.php';
require_once __DIR__ . '/../../config/db.php';

function out_json($code, $success, $message, $data = null) {
    http_response_code($code);
    echo json_encode([
        'success' => (bool)$success,
        'status'  => (bool)$success,
        'message' => $message,
        'data'    => $data
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

if (function_exists('is_logged_in') && !is_logged_in()) {
    out_json(401, false, 'লগইন প্রয়োজন', null);
}

if (!isset($pdo) || !($pdo instanceof PDO)) {
    out_json(500, false, 'Database connection পাওয়া যায়নি', null);
}

try {
    // ===== Item types =====
    $items = $pdo->query("
        SELECT id, item_type, item_type_bn, acceptable_wastage_percent
        FROM karigar_wastage_settings
        WHERE is_active = 1
        ORDER BY sort_order, item_type
    ")->fetchAll(PDO::FETCH_ASSOC);

    foreach ($items as &$it) {
        $it['id']                         = (int)$it['id'];
        $it['acceptable_wastage_percent'] = (float)$it['acceptable_wastage_percent'];
    }
    unset($it);

    // ===== Latest gold rate =====
    $rate = $pdo->query("
        SELECT rate_date, rate_24k, rate_22k, rate_21k, rate_18k
        FROM gold_rates
        ORDER BY rate_date DESC
        LIMIT 1
    ")->fetch(PDO::FETCH_ASSOC);

    $gold_rates = [
        'rate_date' => $rate['rate_date'] ?? null,
        'rate_24k'  => (float)($rate['rate_24k'] ?? 0),
        'rate_22k'  => (float)($rate['rate_22k'] ?? 0),
        'rate_21k'  => (float)($rate['rate_21k'] ?? 0),
        'rate_18k'  => (float)($rate['rate_18k'] ?? 0),
        // Per gram conversion (1 vori = 11.664g)
        'per_gram_24k' => round((float)($rate['rate_24k'] ?? 0) / 11.664, 2),
        'per_gram_22k' => round((float)($rate['rate_22k'] ?? 0) / 11.664, 2),
        'per_gram_21k' => round((float)($rate['rate_21k'] ?? 0) / 11.664, 2),
        'per_gram_18k' => round((float)($rate['rate_18k'] ?? 0) / 11.664, 2),
    ];

    // ===== Pending issues by karigar (for related_issue dropdown helper) =====
    // এটা পরে দরকার হলে call হবে — এখন placeholder

    out_json(200, true, 'OK', [
        'items'      => $items,
        'gold_rates' => $gold_rates
    ]);

} catch (Throwable $e) {
    out_json(500, false, 'সার্ভার ত্রুটি: ' . $e->getMessage(), null);
}
