<?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'");

// ✅ Always correct BD time
$now = (new DateTime("now", new DateTimeZone("Asia/Dhaka")))->format("Y-m-d H:i:s");

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

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

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

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

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

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

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

// ✅ Authorization 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 check
$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'];

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

// ✅ Pagination calculation
$offset = ($pageNo - 1) * $pageSize;

// ✅ Total count
$countQuery = mysqli_query($conn, "
    SELECT COUNT(*) as total 
    FROM hodike_balakedara 
    WHERE userkani='$userId'
");
$totalRow = mysqli_fetch_assoc($countQuery);
$totalCount = (int)$totalRow['total'];

// ✅ Fetch paginated data
$listQuery = mysqli_query($conn, "
    SELECT price, shonu 
    FROM hodike_balakedara 
    WHERE userkani='$userId'
    ORDER BY shonu DESC
    LIMIT $offset, $pageSize
");

// ✅ Build list
$data = [];
$data['list'] = [];

while ($row = mysqli_fetch_assoc($listQuery)) {
    $data['list'][] = [
        'addTime' => $row['shonu'], // already BD time
        'amount'  => (int)$row['price']
    ];
}

// ✅ Pagination info
$data['pageNo'] = $pageNo;
$data['totalPage'] = $pageSize > 0 ? ceil($totalCount / $pageSize) : 0;
$data['totalCount'] = $totalCount;

// ✅ Final response
echo json_encode([
    'code' => 0,
    'msg' => 'Succeed',
    'msgCode' => 0,
    'serviceNowTime' => $now,
    'data' => $data
]);
?>