<?php
require __DIR__.'/_bootstrap.php';

use Zoo\Database;
use Zoo\Auth\PlayerAuthService;

try{
    $in=input_json();
    $db=Database::connect();
    $player=(new PlayerAuthService($db))->authenticate($in);

    $provider=(string)($in['provider']??'');
    $amount=round((float)($in['amount']??0),2);
    $mobile=preg_replace('/\D+/','',(string)($in['mobile']??''));

    if(!in_array($provider,['jazzcash','easypaisa'],true)){
        throw new RuntimeException('Unsupported payment provider');
    }
    if($amount<100 || $amount>1000000){
        throw new RuntimeException('Recharge amount must be between PKR 100 and PKR 1,000,000');
    }
    if(strlen($mobile)===10 && str_starts_with($mobile,'3'))$mobile='0'.$mobile;
    if(strlen($mobile)!==11 || !str_starts_with($mobile,'03')){
        throw new RuntimeException('Enter a valid Pakistani mobile number');
    }

    $q=$db->prepare("
      SELECT * FROM payment_gateway_config
      WHERE provider_code=? LIMIT 1
    ");
    $q->execute([$provider]);
    $cfg=$q->fetch(PDO::FETCH_ASSOC);
    if(!$cfg || (int)$cfg['enabled']!==1){
        throw new RuntimeException(
            ucfirst($provider).' merchant gateway is awaiting merchant credentials'
        );
    }

    /*
     * Safety: do not create a charge until the real provider adapter is enabled.
     * This prevents fake or accidental "successful" deposits.
     */
    throw new RuntimeException(
        'Gateway credentials are present but provider request mapping is not enabled yet'
    );

}catch(Throwable $e){
    json_out(['ok'=>false,'error'=>$e->getMessage()],422);
}
