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

use Zoo\Database;
use Zoo\Admin\AdminApiAuth;

try{
    AdminApiAuth::requireKey();
    $db=Database::connect();

    if($_SERVER['REQUEST_METHOD']==='POST'){
        $in=input_json();
        $code=trim((string)($in['code']??''));
        if(!in_array($code,['jazzcash','easypaisa'],true)){
            throw new RuntimeException('Only JazzCash and Easypaisa are editable here');
        }

        $destination=trim((string)($in['destination_value']??''));
        $label=trim((string)($in['destination_label']??''));
        $instructions=trim((string)($in['instructions']??''));
        $min=round((float)($in['min_amount']??100),2);
        $max=round((float)($in['max_amount']??1000000),2);
        $enabled=!empty($in['enabled']) ? 1 : 0;

        if($min<=0 || $max<$min) throw new RuntimeException('Invalid deposit limits');
        if($enabled && $destination==='') throw new RuntimeException('Add the payment destination before enabling this method');
        if(strlen($destination)>255) throw new RuntimeException('Destination is too long');
        if(strlen($label)>100) throw new RuntimeException('Destination label is too long');

        $q=$db->prepare("
            UPDATE player_deposit_methods
            SET destination_label=?,
                destination_value=?,
                instructions=?,
                min_amount=?,
                max_amount=?,
                enabled=?,
                updated_at=NOW()
            WHERE code=?
        ");
        $q->execute([
            $label!==''?$label:($code==='jazzcash'?'JazzCash Number':'Easypaisa Number'),
            $destination,$instructions,$min,$max,$enabled,$code
        ]);
    }

    $q=$db->query("
        SELECT code,name,type,currency,min_amount,max_amount,
               destination_label,destination_value,instructions,enabled,sort_order,updated_at
        FROM player_deposit_methods
        WHERE code IN ('jazzcash','easypaisa')
        ORDER BY sort_order,id
    ");

    json_out(['ok'=>true,'methods'=>$q->fetchAll(PDO::FETCH_ASSOC)]);
}catch(Throwable $e){
    json_out(['ok'=>false,'error'=>$e->getMessage()],422);
}
