<?php
declare(strict_types=1);

if (!defined('AYCORE_SKIP_BOTAPI_ROUTER')) define('AYCORE_SKIP_BOTAPI_ROUTER', true);
require_once dirname(__DIR__) . '/config.php';
require_once dirname(__DIR__) . '/botapi.php';

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

function itz_commerce_json(int $status, array $payload): never {
    http_response_code($status);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    exit;
}

$commerce = $GLOBALS['itzCommerce'] ?? null;
if (!$commerce instanceof \iTz\Commerce\Commerce) itz_commerce_json(503,['ok'=>false,'error'=>'commerce_unavailable']);

$method = strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET'));
$raw = (string)file_get_contents('php://input');
$body = [];
if ($raw !== '') {
    $decoded = json_decode($raw,true);
    if (is_array($decoded)) $body=$decoded;
}
$headers = function_exists('getallheaders') ? (getallheaders() ?: []) : [];
$h=[]; foreach($headers as $k=>$v)$h[strtolower((string)$k)]=$v;
$apiKey = trim((string)($h['x-itz-key'] ?? $h['authorization'] ?? $_SERVER['HTTP_X_ITZ_KEY'] ?? $_SERVER['HTTP_AUTHORIZATION'] ?? ''));
if (stripos($apiKey,'Bearer ')===0) $apiKey=trim(substr($apiKey,7));
$ts = trim((string)($h['x-itz-timestamp'] ?? $_SERVER['HTTP_X_ITZ_TIMESTAMP'] ?? ''));
$sig = trim((string)($h['x-itz-signature'] ?? $_SERVER['HTTP_X_ITZ_SIGNATURE'] ?? ''));
$site = $commerce->authenticate($apiKey,$ts,$sig,$raw);
if (!$site) itz_commerce_json(401,['ok'=>false,'error'=>'invalid_signature','message'=>'Site authentication failed.']);

$action = trim((string)($_GET['action'] ?? $body['action'] ?? 'health'));
try {
    switch ($action) {
        case 'health':
            itz_commerce_json(200,['ok'=>true,'product'=>'iTzAYDiN-BOT','module'=>'commerce','version'=>'8.0.0','time'=>time()]);
        case 'catalog':
            $products=[];
            foreach($commerce->products(true) as $p){
                $products[]=[
                    'id'=>(int)$p['id'],'title'=>$p['title'],'slug'=>$p['slug'],'description'=>$p['description_text'],
                    'price'=>(float)$p['price'],'currency'=>$p['currency'],'fulfillment_type'=>$p['fulfillment_type'],
                    'parameters'=>json_decode((string)($p['parameter_schema_json']??'[]'),true)?:[],
                    'stock_count'=>(int)$p['stock_count'],
                ];
            }
            itz_commerce_json(200,['ok'=>true,'products'=>$products]);
        case 'payment.methods':
            itz_commerce_json(200,['ok'=>true,'methods'=>$commerce->gatewaySnapshot(),'note'=>'Only safe gateway capability/status metadata is exposed; credentials are never returned.']);
        case 'order.create':
            if($method!=='POST')itz_commerce_json(405,['ok'=>false,'error'=>'method_not_allowed']);
            $order=$commerce->createOrder((int)$site['id'],$body);
            $commerce->notifyAdmin($order,'🛒 سفارش جدید از سایت');
            $commerce->notifyCustomer($order,'order');
            itz_commerce_json(201,['ok'=>true,'order'=>['public_id'=>$order['public_id'],'status'=>$order['status_name'],'payment_status'=>$order['payment_status'],'total_amount'=>(float)$order['total_amount'],'currency'=>$order['currency']]]);
        case 'order.parameters':
            if($method!=='POST')itz_commerce_json(405,['ok'=>false,'error'=>'method_not_allowed']);
            $public=trim((string)($body['public_id']??''));$order=$commerce->orderByPublic($public,(int)$site['id']);
            if(!$order)itz_commerce_json(404,['ok'=>false,'error'=>'order_not_found']);
            $params=is_array($body['parameters']??null)?$body['parameters']:[];
            $order=$commerce->updateParameters((int)$order['id'],$params,'website');
            $commerce->notifyAdmin($order,'📝 اطلاعات سفارش سایت تکمیل شد');
            itz_commerce_json(200,['ok'=>true,'order'=>['public_id'=>$order['public_id'],'status'=>$order['status_name']]]);
        case 'payment.success':
            if($method!=='POST')itz_commerce_json(405,['ok'=>false,'error'=>'method_not_allowed']);
            $public=trim((string)($body['public_id']??''));$order=$commerce->orderByPublic($public,(int)$site['id']);
            if(!$order)itz_commerce_json(404,['ok'=>false,'error'=>'order_not_found']);
            $wasPaid=((string)($order['payment_status']??'')==='paid');
            $order=$commerce->markPayment((int)$order['id'],true,$body);
            if(!$wasPaid){$commerce->notifyAdmin($order,'✅ پرداخت سفارش سایت تایید شد');$commerce->notifyCustomer($order,'paid');}
            itz_commerce_json(200,['ok'=>true,'order'=>['public_id'=>$order['public_id'],'status'=>$order['status_name'],'payment_status'=>$order['payment_status']]]);
        case 'payment.failed':
            if($method!=='POST')itz_commerce_json(405,['ok'=>false,'error'=>'method_not_allowed']);
            $public=trim((string)($body['public_id']??''));$order=$commerce->orderByPublic($public,(int)$site['id']);
            if(!$order)itz_commerce_json(404,['ok'=>false,'error'=>'order_not_found']);
            $order=$commerce->markPayment((int)$order['id'],false,$body);
            $commerce->notifyAdmin($order,'❌ پرداخت سفارش سایت ناموفق بود');
            itz_commerce_json(200,['ok'=>true]);
        case 'order.status':
            $public=trim((string)($_GET['public_id']??$body['public_id']??''));$order=$commerce->orderByPublic($public,(int)$site['id']);
            if(!$order)itz_commerce_json(404,['ok'=>false,'error'=>'order_not_found']);
            itz_commerce_json(200,['ok'=>true,'order'=>['public_id'=>$order['public_id'],'status'=>$order['status_name'],'payment_status'=>$order['payment_status'],'parameters'=>json_decode((string)($order['parameters_json']??'{}'),true)?:[],'updated_at'=>(int)$order['updated_at']]]);
        default:
            itz_commerce_json(404,['ok'=>false,'error'=>'unknown_action']);
    }
} catch (InvalidArgumentException $e) {
    itz_commerce_json(422,['ok'=>false,'error'=>'validation_error','message'=>$e->getMessage()]);
} catch (Throwable $e) {
    error_log('[commerce api] '.$e->getMessage());
    itz_commerce_json(500,['ok'=>false,'error'=>'internal_error','message'=>'Commerce request failed.']);
}
