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

use Zoo\Database;
use Zoo\Admin\AdminApiAuth;
use Zoo\Deposit\DepositService;

try{
    AdminApiAuth::requireKey();
    $in=input_json();
    $depositId=(int)($in['deposit_id']??0);
    $action=trim((string)($in['action']??''));
    $providerRef=trim((string)($in['provider_reference']??''));
    $note=trim((string)($in['note']??''));

    if($depositId<=0) throw new RuntimeException('Invalid deposit ID');
    $db=Database::connect();

    if($action==='confirm'){
        if($providerRef==='') throw new RuntimeException('Provider/payment reference is required');
        $d=(new DepositService($db))->confirm($depositId,$providerRef);
        json_out(['ok'=>true,'deposit'=>$d]);
    }

    if($action==='reject'){
        $db->beginTransaction();
        try{
            $q=$db->prepare("SELECT id,status FROM player_deposits WHERE id=? FOR UPDATE");
            $q->execute([$depositId]);
            $d=$q->fetch(PDO::FETCH_ASSOC);
            if(!$d || $d['status']!=='pending') throw new RuntimeException('Pending deposit not found');

            $q=$db->prepare("
              UPDATE player_deposits
              SET status='rejected',provider_reference=NULL,updated_at=NOW()
              WHERE id=? AND status='pending'
            ");
            $q->execute([$depositId]);
            if($q->rowCount()!==1) throw new RuntimeException('Deposit status changed; refresh cashier');
            $db->commit();
            json_out(['ok'=>true,'deposit'=>['id'=>$depositId,'status'=>'rejected','admin_note'=>$note]]);
        }catch(Throwable $e){
            if($db->inTransaction())$db->rollBack();
            throw $e;
        }
    }

    throw new RuntimeException('Unsupported deposit action');
}catch(Throwable $e){
    json_out(['ok'=>false,'error'=>$e->getMessage()],422);
}
