<?php
/**
 * Admin Discount Codes Management API
 */

require_once 'config.php';

// Handle both GET and POST (JSON)
$input = json_decode(file_get_contents('php://input'), true) ?: [];
$userId = miniapp_require_admin();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // لیست کدهای تخفیف
    try {
        $stmt = $pdo->query("SELECT * FROM discount_codes ORDER BY created_at DESC");
        $discounts = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['ok' => true, 'data' => ['discounts' => $discounts]]);
    } catch (PDOException $e) {
        // جدول وجود ندارد
        echo json_encode(['ok' => true, 'data' => ['discounts' => [], 'notice' => 'جدول کدهای تخفیف هنوز ایجاد نشده. SQL را اجرا کنید.']]);
    }
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $input['action'] ?? '';
    
    if ($action === 'add') {
        $code = strtoupper(trim($input['code'] ?? ''));
        $type = $input['type'] ?? 'PERCENT';
        $value = (int)($input['value'] ?? 0);
        $paymentScope = strtolower(trim((string)($input['payment_scope'] ?? 'all')));
        if (!in_array($paymentScope, ['all','card','crypto'], true)) $paymentScope = 'all';
        
        if (strlen($code) < 3) {
            echo json_encode(['ok' => false, 'error' => 'کد باید حداقل ۳ کاراکتر باشد']);
            exit;
        }
        
        // چک تکراری نبودن
        $stmt = $pdo->prepare("SELECT id FROM discount_codes WHERE code = ?");
        $stmt->execute([$code]);
        if ($stmt->fetch()) {
            echo json_encode(['ok' => false, 'error' => 'این کد قبلاً ثبت شده']);
            exit;
        }
        
        $stmt = $pdo->prepare("
            INSERT INTO discount_codes (code, type, value, payment_scope, created_by)
            VALUES (?, ?, ?, ?, ?)
        ");
        $stmt->execute([$code, $type, $value, $paymentScope, $userId]);
        gemaccAdminActionNotify('کد تخفیف جدید اضافه شد', ['کد'=>$code, 'نوع'=>$type, 'مقدار'=>$value, 'محدوده پرداخت'=>$paymentScope], $userId);
        
        echo json_encode(['ok' => true, 'message' => 'کد تخفیف اضافه شد']);
        exit;
    }
    
    if ($action === 'toggle') {
        $discountId = (int)($input['discount_id'] ?? 0);
        
        $stmt = $pdo->prepare("SELECT is_active FROM discount_codes WHERE id = ?");
        $stmt->execute([$discountId]);
        $discount = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($discount) {
            $newStatus = $discount['is_active'] ? 0 : 1;
            $stmt = $pdo->prepare("UPDATE discount_codes SET is_active = ? WHERE id = ?");
            $stmt->execute([$newStatus, $discountId]);
            gemaccAdminActionNotify($newStatus ? 'کد تخفیف فعال شد' : 'کد تخفیف غیرفعال شد', ['شناسه کد'=>$discountId], $userId);
        }
        
        echo json_encode(['ok' => true, 'message' => 'وضعیت تغییر کرد']);
        exit;
    }
    
    if ($action === 'delete') {
        $discountId = (int)($input['discount_id'] ?? 0);
        
        $stmt = $pdo->prepare("DELETE FROM discount_codes WHERE id = ?");
        $stmt->execute([$discountId]);
        gemaccAdminActionNotify('کد تخفیف حذف شد', ['شناسه کد'=>$discountId], $userId);
        
        echo json_encode(['ok' => true, 'message' => 'کد حذف شد']);
        exit;
    }
    

    if ($action === 'broadcast_discount') {
        $discountId=(int)($input['discount_id']??0);
        $target=$input['target']??'all';
        $message=trim((string)($input['message']??''));
        $photo=trim((string)($input['photo_file_id']??''));
        $st=$pdo->prepare("SELECT * FROM discount_codes WHERE id=? LIMIT 1"); $st->execute([$discountId]); $d=$st->fetch(PDO::FETCH_ASSOC);
        if(!$d){ echo json_encode(['ok'=>false,'error'=>'کد تخفیف پیدا نشد'], JSON_UNESCAPED_UNICODE); exit; }
        if($target==='buyers') $q="SELECT DISTINCT u.id FROM users u JOIN orders o ON o.user_id=u.id AND o.status='DELIVERED' WHERE COALESCE(u.is_blocked,0)=0";
        elseif($target==='non_buyers') $q="SELECT u.id FROM users u LEFT JOIN orders o ON o.user_id=u.id AND o.status='DELIVERED' WHERE o.id IS NULL AND COALESCE(u.is_blocked,0)=0";
        else $q="SELECT id FROM users WHERE COALESCE(is_blocked,0)=0";
        $users=$pdo->query($q)->fetchAll(PDO::FETCH_COLUMN);
        $txt="🎁 <b>کد تخفیف ویژه GEM ACC</b>

".($message!==''?htmlspecialchars($message,ENT_QUOTES,'UTF-8')."

":'')."🎫 کد تخفیف قابل کپی:
<code>".htmlspecialchars($d['code'],ENT_QUOTES,'UTF-8')."</code>";
        $sent=0; $failed=0;
        foreach($users as $uid){
            $params=['chat_id'=>(int)$uid,'parse_mode'=>'HTML'];
            if($photo!==''){ $params['photo']=$photo; $params['caption']=$txt; $res=tg('sendPhoto',$params); }
            else { $params['text']=$txt; $res=tg('sendMessage',$params); }
            if($res && !empty($res['ok'])) $sent++; else $failed++;
            if(($sent+$failed)%25===0) usleep(250000);
        }
        $pdo->prepare("INSERT INTO broadcast_logs(admin_id,message,target_type,total_users,sent_count,failed_count,blocked_count) VALUES(?,?,?,?,?,?,0)")->execute([$userId,$txt,'discount_'.$target,count($users),$sent,$failed]);
        gemaccAdminActionNotify('ارسال گروهی کد تخفیف انجام شد', ['کد'=>$d['code'] ?? $discountId, 'گروه هدف'=>$target, 'کل'=>count($users), 'ارسال موفق'=>$sent, 'ناموفق'=>$failed], $userId);
        echo json_encode(['ok'=>true,'message'=>'ارسال انجام شد','sent'=>$sent,'failed'=>$failed,'total'=>count($users)], JSON_UNESCAPED_UNICODE); exit;
    }
    echo json_encode(['ok' => false, 'error' => 'عملیات نامعتبر']);
}

