<?php
require_once 'config.php';
header('Content-Type: application/json; charset=utf-8');
$userId = miniapp_require_admin();
function asp_ensure(PDO $pdo): void {
    try { $pdo->exec("CREATE TABLE IF NOT EXISTS sms_payment_events (id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, sms_hash CHAR(64) NOT NULL, sender VARCHAR(120) DEFAULT NULL, body_text MEDIUMTEXT NOT NULL, amount_rial BIGINT DEFAULT NULL, received_at DATETIME DEFAULT NULL, uploaded_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, status VARCHAR(30) NOT NULL DEFAULT 'received', matched_order_id BIGINT UNSIGNED DEFAULT NULL, match_count INT NOT NULL DEFAULT 0, error_text TEXT DEFAULT NULL, raw_json LONGTEXT DEFAULT NULL, PRIMARY KEY(id), UNIQUE KEY uq_sms_hash(sms_hash), KEY idx_amount_received(amount_rial,received_at), KEY idx_status_uploaded(status,uploaded_at), KEY idx_matched_order(matched_order_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"); } catch(Throwable $e) {}
    try { $pdo->exec("CREATE TABLE IF NOT EXISTS sms_payment_matches (id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, event_id BIGINT UNSIGNED NOT NULL, order_id BIGINT UNSIGNED NOT NULL, amount_rial BIGINT NOT NULL, match_status VARCHAR(30) NOT NULL DEFAULT 'matched', approved_at DATETIME DEFAULT NULL, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, note TEXT DEFAULT NULL, PRIMARY KEY(id), UNIQUE KEY uq_event_order(event_id,order_id), UNIQUE KEY uq_order_once(order_id), KEY idx_event(event_id), KEY idx_status(match_status)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"); } catch(Throwable $e) {}
}
function asp_setting(PDO $pdo,string $k,string $d=''): string { try{$st=$pdo->prepare("SELECT value FROM settings WHERE key_name=?");$st->execute([$k]);$v=$st->fetchColumn();return $v===false?$d:(string)$v;}catch(Throwable $e){return $d;} }
function asp_set(PDO $pdo,string $k,string $v): void { $st=$pdo->prepare("INSERT INTO settings(key_name,value) VALUES(?,?) ON DUPLICATE KEY UPDATE value=VALUES(value)"); $st->execute([$k,$v]); }
try{
    asp_ensure($pdo);
    $input=json_decode(file_get_contents('php://input'),true) ?: $_POST;
    $action=(string)($input['action'] ?? $_GET['action'] ?? 'list');
    if($action==='settings'){
        echo json_encode(['ok'=>true,'data'=>[
            'enabled'=>asp_setting($pdo,'sms_auto_approve_enabled','1'),
            'window_hours'=>asp_setting($pdo,'sms_auto_approve_window_hours','48'),
            'tolerance_rial'=>asp_setting($pdo,'sms_auto_approve_tolerance_rial','0'),
            'require_receipt'=>'0',
            'allowed_senders'=>asp_setting($pdo,'sms_auto_approve_allowed_senders',''),
            'notify_admins'=>asp_setting($pdo,'sms_auto_approve_notify_admins','1'),
        ]], JSON_UNESCAPED_UNICODE); exit;
    }
    if($action==='save_settings'){
        asp_set($pdo,'sms_auto_approve_enabled', !empty($input['enabled']) ? '1':'0');
        asp_set($pdo,'sms_auto_approve_window_hours', (string)max(1,min(240,(int)($input['window_hours'] ?? 48))));
        asp_set($pdo,'sms_auto_approve_tolerance_rial', (string)max(0,(int)($input['tolerance_rial'] ?? 0)));
        asp_set($pdo,'sms_auto_approve_require_receipt', '0');
        asp_set($pdo,'sms_auto_approve_allowed_senders', trim((string)($input['allowed_senders'] ?? '')));
        asp_set($pdo,'sms_auto_approve_notify_admins', !empty($input['notify_admins']) ? '1':'0');
        echo json_encode(['ok'=>true,'message'=>'تنظیمات ذخیره شد'], JSON_UNESCAPED_UNICODE); exit;
    }
    $limit=max(10,min(100,(int)($_GET['limit'] ?? 50)));
    $st=$pdo->query("SELECT e.*, m.match_status, m.order_id AS match_order_id FROM sms_payment_events e LEFT JOIN sms_payment_matches m ON m.event_id=e.id ORDER BY e.uploaded_at DESC, e.id DESC LIMIT {$limit}");
    $items=$st->fetchAll(PDO::FETCH_ASSOC);
    foreach($items as &$x){
        $x['id']=(int)$x['id']; $x['amount_rial']=isset($x['amount_rial'])?(int)$x['amount_rial']:0; $x['matched_order_id']=(int)($x['matched_order_id'] ?: $x['match_order_id'] ?: 0); $x['match_count']=(int)($x['match_count'] ?? 0);
    }
    echo json_encode(['ok'=>true,'data'=>['events'=>$items]], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}catch(Throwable $e){ echo json_encode(['ok'=>false,'error'=>$e->getMessage()], JSON_UNESCAPED_UNICODE); }
