<?php
require_once '../../config/db.php';
require_once '../../config/session.php';
require_once '../../config/response.php';

session_start_if_not_started();

if (!is_logged_in()) {
    send_response(401, false, 'অনুমতি নেই');
}

$location_id = $_GET['location_id'] ?? null;

try {
    // সব লোকেশনের স্টক
    if (!$location_id) {
        $stmt = $pdo->prepare(
            "SELECT 
                sl.name AS location_name,
                sl.name_bn AS location_name_bn,
                sl.type AS location_type,
                gs.karat,
                gs.weight_gram,
                gs.pure_weight,
                gr.rate_24k,
                ROUND(gs.pure_weight * gr.rate_24k, 2) 
                    AS stock_value
             FROM gold_stock gs
             JOIN stock_locations sl 
                ON gs.location_id = sl.id
             LEFT JOIN gold_rates gr 
                ON gr.rate_date = CURDATE()
             ORDER BY sl.id, gs.karat"
        );
        $stmt->execute();
    } else {
        // নির্দিষ্ট লোকেশনের স্টক
        $stmt = $pdo->prepare(
            "SELECT 
                sl.name AS location_name,
                sl.name_bn AS location_name_bn,
                sl.type AS location_type,
                gs.karat,
                gs.weight_gram,
                gs.pure_weight,
                gr.rate_24k,
                ROUND(gs.pure_weight * gr.rate_24k, 2) 
                    AS stock_value
             FROM gold_stock gs
             JOIN stock_locations sl 
                ON gs.location_id = sl.id
             LEFT JOIN gold_rates gr 
                ON gr.rate_date = CURDATE()
             WHERE gs.location_id = :location_id
             ORDER BY gs.karat"
        );
        $stmt->execute([':location_id' => $location_id]);
    }

    $stocks = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // মোট স্টক হিসাব
    $total_weight = 0;
    $total_pure   = 0;
    $total_value  = 0;

    foreach ($stocks as $stock) {
        $total_weight += $stock['weight_gram'];
        $total_pure   += $stock['pure_weight'];
        $total_value  += $stock['stock_value'];
    }

    send_response(200, true, 'সফল', [
        'stocks'       => $stocks,
        'total_weight' => round($total_weight, 3),
        'total_pure'   => round($total_pure, 3),
        'total_value'  => round($total_value, 2)
    ]);

} catch (Exception $e) {
    send_response(500, false, 'সার্ভার সমস্যা: ' . $e->getMessage());
}
?>