<?php
require_once 'config.php';
header('Content-Type: application/json; charset=utf-8');
$userId = (int)($_GET['user_id'] ?? $_POST['user_id'] ?? 0);
if (!$userId) { echo json_encode(['ok'=>false,'error'=>'user_id required'], JSON_UNESCAPED_UNICODE); exit; }
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS user_discount_codes (id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, user_id BIGINT NOT NULL, discount_id INT UNSIGNED NULL, code VARCHAR(50) NOT NULL, title VARCHAR(255) NULL, message TEXT NULL, source VARCHAR(50) DEFAULT 'admin', is_active TINYINT(1) NOT NULL DEFAULT 1, used_at DATETIME NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY(id), UNIQUE KEY uniq_user_code(user_id,code), INDEX idx_udc_user(user_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
    $codes=[];
    $stmt=$pdo->prepare("SELECT udc.*, dc.type, dc.value, dc.payment_scope, dc.broadcast_message FROM user_discount_codes udc LEFT JOIN discount_codes dc ON dc.code=udc.code WHERE udc.user_id=? AND udc.is_active=1 ORDER BY udc.used_at IS NULL DESC, udc.created_at DESC");
    $stmt->execute([$userId]);
    foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $r){
        $codes[strtoupper($r['code'])]=['code'=>strtoupper($r['code']),'title'=>$r['title'] ?: 'کد تخفیف اختصاصی','message'=>($r['message'] ?: ($r['broadcast_message'] ?? '')),'used'=>!empty($r['used_at']),'created_at'=>$r['created_at'],'type'=>$r['type'],'value'=>(int)($r['value']??0),'payment_scope'=>($r['payment_scope'] ?? 'all'),'source'=>$r['source'] ?: 'admin'];
    }
    $g=$pdo->prepare("SELECT dc.* FROM discount_codes dc WHERE dc.is_active=1 AND (dc.valid_from IS NULL OR dc.valid_from<=NOW()) AND (dc.valid_until IS NULL OR dc.valid_until>=NOW()) AND (dc.max_uses IS NULL OR dc.used_count<dc.max_uses) AND (SELECT COUNT(*) FROM discount_usages du WHERE du.discount_id=dc.id AND du.user_id=?) < GREATEST(1, dc.max_uses_per_user) ORDER BY dc.created_at DESC LIMIT 20");
    $g->execute([$userId]);
    foreach($g->fetchAll(PDO::FETCH_ASSOC) as $r){
        $code=strtoupper($r['code']);
        if(!isset($codes[$code])) $codes[$code]=['code'=>$code,'title'=>'کد تخفیف همگانی','message'=>($r['broadcast_message'] ?: 'کد تخفیف جشنواره‌ای قابل استفاده برای سفارش شما'),'used'=>false,'created_at'=>$r['created_at'],'type'=>$r['type'],'value'=>(int)($r['value']??0),'payment_scope'=>($r['payment_scope'] ?? 'all'),'source'=>'global'];
    }
    $codes=array_values($codes);
    echo json_encode(['ok'=>true,'data'=>['codes'=>$codes]], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
} catch(Throwable $e){ echo json_encode(['ok'=>false,'error'=>$e->getMessage()], JSON_UNESCAPED_UNICODE); }
