<?php 
include "../../conn.php";
include "../../functions2.php";

header('Content-Type: application/json; charset=utf-8');
header('Strict-Transport-Security: max-age=31536000');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
header('Access-Control-Allow-Credentials: true');

// ✅ CORS
$origin = $_SERVER['HTTP_ORIGIN'] ?? '*';
header('Access-Control-Allow-Origin: ' . $origin);
header('Vary: Origin');

// ✅ Bangladesh Time FIX (PHP + MySQL)
date_default_timezone_set("Asia/Dhaka");
mysqli_query($conn, "SET time_zone = '+06:00'");

// ✅ Current BD Time (100% accurate)
$dt = new DateTime("now", new DateTimeZone("Asia/Dhaka"));
$currentTime = $dt->format("Y-m-d H:i:s");

$response = [
    'code' => 11,
    'msg' => 'Method not allowed',
    'msgCode' => 12,
    'serviceNowTime' => $currentTime,
];

// ❌ Only POST allowed
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode($response);
    exit;
}

// ✅ Input JSON
$input = json_decode(file_get_contents("php://input"), true);

// ✅ Validate params
if (!isset($input['giftCode'], $input['language'], $input['random'], $input['signature'], $input['timestamp'])) {
    echo json_encode([
        'code' => 7,
        'msg' => 'Param is Invalid',
        'msgCode' => 6
    ]);
    exit;
}

// ✅ Sanitize
$giftCode = mysqli_real_escape_string($conn, $input['giftCode']);
$language = (int)$input['language'];
$random = mysqli_real_escape_string($conn, $input['random']);
$signature = strtoupper($input['signature']);

// ✅ Signature check
$signStr = '{"giftCode":"'.$giftCode.'","language":'.$language.',"random":"'.$random.'"}';
$localSign = strtoupper(md5($signStr));

if ($localSign !== $signature) {
    echo json_encode([
        'code' => 5,
        'msg' => 'Wrong signature',
        'msgCode' => 3
    ]);
    exit;
}

// ✅ Auth check
if (!isset($_SERVER['HTTP_AUTHORIZATION'])) {
    http_response_code(401);
    echo json_encode(['code'=>4,'msg'=>'No operation permission','msgCode'=>2]);
    exit;
}

$bearer = explode(" ", $_SERVER['HTTP_AUTHORIZATION']);
$token = $bearer[1] ?? '';

$jwt = json_decode(is_jwt_valid($token), true);

if ($jwt['status'] !== 'Success') {
    http_response_code(401);
    echo json_encode(['code'=>4,'msg'=>'No operation permission','msgCode'=>2]);
    exit;
}

// ✅ Session check
$userId = $jwt['payload']['id'];

$ses = mysqli_query($conn, "SELECT akshinak FROM shonu_subjects WHERE akshinak='$token'");
if (mysqli_num_rows($ses) !== 1) {
    http_response_code(401);
    echo json_encode(['code'=>4,'msg'=>'No operation permission','msgCode'=>2]);
    exit;
}

// ✅ Gift code check
$codeQuery = mysqli_query($conn, "
    SELECT utilisateurmax, prix, nombredutilisateurs 
    FROM hodike_nirvahaka 
    WHERE enserie='$giftCode' AND shonu='1'
");

if (mysqli_num_rows($codeQuery) == 0) {
    echo json_encode(['code'=>1,'msg'=>'Redemption code error','msgCode'=>230,'data'=>null]);
    exit;
}

$codeData = mysqli_fetch_assoc($codeQuery);

// ❌ Limit check
if ($codeData['nombredutilisateurs'] >= $codeData['utilisateurmax']) {
    echo json_encode(['code'=>1,'msg'=>'Redemption code error','msgCode'=>230,'data'=>null]);
    exit;
}

// ❌ Already used
$used = mysqli_query($conn, "
    SELECT kani FROM hodike_balakedara 
    WHERE serial='$giftCode' AND userkani='$userId'
");

if (mysqli_num_rows($used) > 0) {
    echo json_encode(['code'=>1,'msg'=>'Redemption code error','msgCode'=>230,'data'=>null]);
    exit;
}

// ✅ Transaction start
mysqli_begin_transaction($conn);

try {
    $prix = $codeData['prix'];

    // ✅ Update usage
    mysqli_query($conn, "
        UPDATE hodike_nirvahaka 
        SET nombredutilisateurs = nombredutilisateurs + 1 
        WHERE enserie='$giftCode'
    ");

    // ✅ Insert redeem (BD time)
    mysqli_query($conn, "
        INSERT INTO hodike_balakedara (userkani, serial, price, shonu)
        VALUES ('$userId','$giftCode','$prix','$currentTime')
    ");

    // ✅ Update balance
    mysqli_query($conn, "
        UPDATE shonu_kaichila
        SET motta = ROUND(motta + '$prix', 2)
        WHERE balakedara='$userId'
    ");

    mysqli_commit($conn);

    echo json_encode([
        'code' => 0,
        'msg' => 'Succeed',
        'msgCode' => 0,
        'serviceNowTime' => $currentTime,
        'data' => null
    ]);

} catch (Exception $e) {
    mysqli_rollback($conn);

    echo json_encode([
        'code' => 500,
        'msg' => 'Server Error',
        'msgCode' => 500
    ]);
}
?>