<?php
// File 3/6
// Path: api/gold/get_rate.php
// Table: gold_rates
// column: rate_date (date নয়!)

header('Content-Type: application/json');
require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../auth/check_session.php';

$date = $_GET['date'] ?? date('Y-m-d');

try {
    $stmt = $pdo->prepare("
        SELECT
            id,
            rate_date  AS date,
            rate_24k,
            rate_22k,
            rate_21k,
            rate_18k,
            created_at
        FROM gold_rates
        WHERE rate_date <= ?
        ORDER BY rate_date DESC
        LIMIT 1
    ");
    $stmt->execute([$date]);
    $rate = $stmt->fetch();

    if (!$rate) {
        echo json_encode([
            'ok'      => false,
            'success' => false,
            'msg'     => 'কোনো রেট পাওয়া যায়নি'
        ]);
        exit;
    }

    echo json_encode([
        'ok'      => true,
        'success' => true,
        'data'    => $rate,
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'msg' => 'Server error']);
}
