<?php
/**
 * User support tickets API - v27.50 hardened ticket/chat flow
 */
require_once 'config.php';
header('Content-Type: application/json; charset=utf-8');

$input = json_decode(file_get_contents('php://input'), true) ?: ($_POST ?: $_GET);
$userId = $input['user_id'] ?? $_GET['user_id'] ?? null;
if (!$userId) { echo json_encode(['ok'=>false,'error'=>'user_id required'], JSON_UNESCAPED_UNICODE); exit; }
$userId = (int)$userId;
if (function_exists('gemaccAdminChatEnsureSchema')) gemaccAdminChatEnsureSchema($pdo);

function support_json($data): void { echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit; }
function support_status_label(string $s): string { return function_exists('gemaccSupportStatusLabel') ? gemaccSupportStatusLabel($s) : $s; }

function support_save_upload(): array {
    if (empty($_FILES['attachment']) || !is_array($_FILES['attachment'])) return [];
    $f=$_FILES['attachment'];
    if (($f['error'] ?? UPLOAD_ERR_NO_FILE)===UPLOAD_ERR_NO_FILE) return [];
    if (($f['error'] ?? UPLOAD_ERR_OK)!==UPLOAD_ERR_OK) throw new RuntimeException('آپلود فایل ناموفق بود');
    if ((int)($f['size']??0)>12*1024*1024) throw new RuntimeException('حداکثر حجم فایل ۱۲ مگابایت است');
    $mime='application/octet-stream';
    $tmp=(string)$f['tmp_name'];
    if(function_exists('finfo_open')){
        $fi=finfo_open(FILEINFO_MIME_TYPE);
        if($fi){$detected=finfo_file($fi,$tmp);if(is_string($detected)&&$detected!=='')$mime=$detected;finfo_close($fi);}
    }
    if(($mime===''||$mime==='application/octet-stream')&&function_exists('mime_content_type')){
        $detected=@mime_content_type($tmp);if(is_string($detected)&&$detected!=='')$mime=$detected;
    }
    if(($mime===''||$mime==='application/octet-stream')&&function_exists('getimagesize')){
        $img=@getimagesize($tmp);if(is_array($img)&&!empty($img['mime']))$mime=(string)$img['mime'];
    }
    $allowed=[
        'image/jpeg'=>['jpg','local_image'],'image/png'=>['png','local_image'],'image/webp'=>['webp','local_image'],'image/gif'=>['gif','local_image'],
        'application/pdf'=>['pdf','local_file'],'text/plain'=>['txt','local_file'],
        'video/mp4'=>['mp4','local_file'],'audio/mpeg'=>['mp3','local_file'],'audio/ogg'=>['ogg','local_file'],
        'application/zip'=>['zip','local_file'],'application/x-zip-compressed'=>['zip','local_file'],
    ];
    if(!isset($allowed[$mime])) throw new RuntimeException('فرمت فایل مجاز نیست؛ تصویر، PDF، متن، ویدئو، صوت یا ZIP ارسال کنید');
    $dir=dirname(__DIR__).'/uploads/support';
    if(!is_dir($dir)&&!mkdir($dir,0755,true)&&!is_dir($dir)) throw new RuntimeException('ساخت پوشه آپلود ممکن نشد');
    $name=bin2hex(random_bytes(16)).'.'.$allowed[$mime][0];
    if(!move_uploaded_file((string)$f['tmp_name'],$dir.'/'.$name)) throw new RuntimeException('ذخیره فایل ناموفق بود');
    return ['type'=>$allowed[$mime][1],'name'=>mb_substr((string)($f['name']??$name),0,250,'UTF-8'),'mime'=>$mime,'path'=>'public/mini_app/uploads/support/'.$name];
}
function support_add_attachment_url(array &$m): void {
    if (!empty($m['telegram_file_id']) || !empty($m['attachment_path'])) {
        $m['attachment_url'] = 'api/support_attachment.php?message_id='.(int)($m['id']??0);
    } else $m['attachment_url']='';
}

try {
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        $ticketId = isset($_GET['ticket_id']) ? (int)$_GET['ticket_id'] : 0;
        if ($ticketId > 0) {
            $stmt = $pdo->prepare("SELECT * FROM support_tickets WHERE id=? AND user_id=?");
            $stmt->execute([$ticketId, $userId]);
            $ticket = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$ticket) support_json(['ok'=>false,'error'=>'تیکت یافت نشد']);
            $stmt = $pdo->prepare("SELECT *, COALESCE(sent_at, created_at) AS message_at FROM support_messages WHERE ticket_id=? ORDER BY COALESCE(sent_at, created_at) ASC, id ASC");
            $stmt->execute([$ticketId]);
            $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
            foreach ($messages as &$m) {
                $at = $m['message_at'] ?? $m['created_at'] ?? null;
                $m['sent_at_formatted'] = $at ? jdate('Y/m/d H:i', strtotime($at)) : '';
                $m['is_mine'] = ((string)($m['sender_role'] ?? '') !== 'ADMIN') && (int)($m['is_admin_reply'] ?? 0) === 0;
                support_add_attachment_url($m);
            }
            try { $pdo->prepare("UPDATE support_messages SET is_read=1 WHERE ticket_id=? AND (sender_role='ADMIN' OR COALESCE(is_admin_reply,0)=1)")->execute([$ticketId]); } catch (Throwable $ignored) {}
            try { $pdo->prepare("UPDATE support_tickets SET unread_user_count=0 WHERE id=?")->execute([$ticketId]); } catch (Throwable $ignored) {}
            $ticket['status_label'] = support_status_label((string)($ticket['status'] ?? 'OPEN'));
            support_json(['ok'=>true,'data'=>['ticket'=>$ticket,'messages'=>$messages]]);
        }
        $stmt = $pdo->prepare("SELECT t.*, (SELECT COUNT(*) FROM support_messages WHERE ticket_id=t.id AND (sender_role='ADMIN' OR COALESCE(is_admin_reply,0)=1) AND is_read=0) AS unread_admin_replies FROM support_tickets t WHERE t.user_id=? ORDER BY COALESCE(t.last_message_at, t.updated_at, t.created_at) DESC, t.id DESC");
        $stmt->execute([$userId]);
        $tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($tickets as &$t) {
            $t['status_label'] = support_status_label((string)($t['status'] ?? 'OPEN'));
            $t['created_at_formatted'] = !empty($t['created_at']) ? jdate('Y/m/d', strtotime($t['created_at'])) : '';
            try {
                $ls = $pdo->prepare("SELECT message_text, sender_role, telegram_file_id, attachment_path, COALESCE(sent_at, created_at) AS at FROM support_messages WHERE ticket_id=? ORDER BY COALESCE(sent_at, created_at) DESC, id DESC LIMIT 1");
                $ls->execute([(int)$t['id']]);
                $lm = $ls->fetch(PDO::FETCH_ASSOC) ?: [];
                $t['last_message'] = trim((string)($lm['message_text'] ?? '')) ?: ((!empty($lm['telegram_file_id']) || !empty($lm['attachment_path'])) ? '📎 فایل/تصویر' : '');
                $t['last_sender_role'] = (string)($lm['sender_role'] ?? '');
                $t['last_message_at'] = (string)($lm['at'] ?? ($t['last_message_at'] ?? $t['updated_at'] ?? ''));
            } catch (Throwable $ignored) {}
        }
        support_json(['ok'=>true,'data'=>['tickets'=>$tickets]]);
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $action = (string)($input['action'] ?? 'send');
        if ($action === 'create') {
            $subject = trim((string)($input['subject'] ?? 'درخواست پشتیبانی'));
            $message = trim((string)($input['message'] ?? ''));
            $attachment = support_save_upload();
            if ($message === '' && !$attachment) support_json(['ok'=>false,'error'=>'متن یا فایل پیام الزامی است']);
            $res = function_exists('gemaccSupportAddUserMessage') ? gemaccSupportAddUserMessage($pdo, $userId, $message, null, $subject, $attachment) : ['ok'=>false,'error'=>'Support service unavailable'];
            support_json($res['ok'] ? ['ok'=>true,'message'=>'تیکت ثبت شد','ticket_id'=>$res['ticket_id']] : ['ok'=>false,'error'=>$res['error'] ?? 'خطا']);
        }
        if ($action === 'send') {
            $ticketId = (int)($input['ticket_id'] ?? 0);
            $message = trim((string)($input['message'] ?? ''));
            $attachment = support_save_upload();
            if ($message === '' && !$attachment) support_json(['ok'=>false,'error'=>'متن یا فایل پیام الزامی است']);
            if ($ticketId > 0) {
                $stmt = $pdo->prepare("SELECT * FROM support_tickets WHERE id=? AND user_id=?");
                $stmt->execute([$ticketId, $userId]);
                $ticket = $stmt->fetch(PDO::FETCH_ASSOC);
                if (!$ticket) support_json(['ok'=>false,'error'=>'تیکت یافت نشد']);
                if (($ticket['status'] ?? '') === 'CLOSED') support_json(['ok'=>false,'error'=>'این تیکت بسته شده است']);
            }
            $res = function_exists('gemaccSupportAddUserMessageToTicket') ? gemaccSupportAddUserMessageToTicket($pdo, $userId, $ticketId, $message, null, 'ادامه تیکت پشتیبانی', $attachment) : (function_exists('gemaccSupportAddUserMessage') ? gemaccSupportAddUserMessage($pdo, $userId, $message, null, 'ادامه تیکت پشتیبانی', $attachment) : ['ok'=>false,'error'=>'Support service unavailable']);
            support_json($res['ok'] ? ['ok'=>true,'message'=>'پیام ارسال شد','ticket_id'=>$res['ticket_id'], 'message_id'=>$res['message_id'] ?? null] : ['ok'=>false,'error'=>$res['error'] ?? 'خطا']);
        }
        if ($action === 'close') {
            $ticketId = (int)($input['ticket_id'] ?? 0);
            if ($ticketId <= 0) support_json(['ok'=>false,'error'=>'ticket_id الزامی است']);
            $stmt = $pdo->prepare("UPDATE support_tickets SET status='CLOSED', closed_at=NOW(), updated_at=NOW() WHERE id=? AND user_id=?");
            $stmt->execute([$ticketId, $userId]);
            support_json(['ok'=>true,'message'=>'تیکت بسته شد']);
        }
        if ($action === 'mark_read') {
            $ticketId = (int)($input['ticket_id'] ?? 0);
            $pdo->prepare("UPDATE support_messages SET is_read=1 WHERE ticket_id=? AND (sender_role='ADMIN' OR COALESCE(is_admin_reply,0)=1)")->execute([$ticketId]);
            $pdo->prepare("UPDATE support_tickets SET unread_user_count=0 WHERE id=?")->execute([$ticketId]);
            support_json(['ok'=>true]);
        }
        support_json(['ok'=>false,'error'=>'Invalid action']);
    }

    support_json(['ok'=>false,'error'=>'Method not allowed']);
} catch (Throwable $e) {
    error_log('[support_api_v50] '.$e->getMessage());
    support_json(['ok'=>false,'error'=>'خطا: '.$e->getMessage()]);
}
