<?php


if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
    die('No direct script access allowed');
}

function createPendingAdminRequest(int $user_id, string $request_type): int {
    try {
        $stmt = pdo()->prepare("INSERT INTO admin_pending_requests (user_id, request_type, status, created_at) VALUES (?, ?, 'pending', NOW())");
        $stmt->execute([$user_id, $request_type]);
        return (int)pdo()->lastInsertId();
    } catch (PDOException $e) {
        if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error creating pending admin request: " . $e->getMessage() . "\n", FILE_APPEND); }
        return 0;
    }
}

function storeAdminRequestMessage(int $request_id, int $admin_user_id, string $platform, int $chat_id, int $message_id): bool {
    try {
        $stmt = pdo()->prepare("INSERT INTO admin_request_messages (request_id, admin_user_id, platform, chat_id, message_id) VALUES (?, ?, ?, ?, ?)");
        return $stmt->execute([$request_id, $admin_user_id, $platform, $chat_id, $message_id]);
    } catch (PDOException $e) {
        if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error storing admin request message: " . $e->getMessage() . "\n", FILE_APPEND); }
        return false;
    }
}

function findPendingRequestByInternalUserId(int $user_id, string $request_type): ?array {
    try {
        $stmt = pdo()->prepare("SELECT * FROM admin_pending_requests WHERE user_id = ? AND request_type = ? AND status = 'pending' ORDER BY id DESC LIMIT 1");
        $stmt->execute([$user_id, $request_type]);
        return $stmt->fetch() ?: null;
    } catch (PDOException $e) {
        if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error finding pending request by user ID {$user_id}: " . $e->getMessage() . "\n", FILE_APPEND); }
        return null;
    }
}

function getPendingRequestMessages(int $request_id): array {
    try {
        $stmt = pdo()->prepare("SELECT * FROM admin_request_messages WHERE request_id = ?");
        $stmt->execute([$request_id]);
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error getting pending request messages for request {$request_id}: " . $e->getMessage() . "\n", FILE_APPEND); }
        return [];
    }
}


function updatePendingRequestStatus(int $request_id, string $status, int $processed_by_admin_id): bool {
    try {
        $stmt = pdo()->prepare("UPDATE admin_pending_requests SET status = ?, processed_at = NOW(), processed_by_admin_id = ? WHERE id = ? AND status = 'pending'");
        $stmt->execute([$status, $processed_by_admin_id, $request_id]);
        return $stmt->rowCount() > 0;
    } catch (PDOException $e) {
        
if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error updating pending request status for {$request_id}: " . $e->getMessage() . "\n", FILE_APPEND); }
        return false;
    }
}

function countPendingAdminRequests(): int {
    try {
        return (int)pdo()->query("SELECT COUNT(*) FROM admin_pending_requests WHERE status = 'pending'")->fetchColumn();
    } catch (PDOException $e) {
        if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error counting pending admin requests: " . $e->getMessage() . "\n", FILE_APPEND); }
        return 0;
    }
}

function getPendingAdminRequests(int $offset, int $limit): array {
    try {
        $stmt = pdo()->prepare("
            SELECT pr.id, pr.request_type, pr.created_at, u.id as user_id, u.first_name, u.phone_number
            FROM admin_pending_requests pr
            JOIN users u ON pr.user_id = u.id
            WHERE pr.status = 'pending'
            ORDER BY pr.created_at DESC
            LIMIT :limit OFFSET :offset
        ");
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error getting pending admin requests: " . $e->getMessage() . "\n", FILE_APPEND); }
        return [];
    }
}

function getPendingRequestById(int $request_id): ?array {
    try {
        $stmt = pdo()->prepare("SELECT * FROM admin_pending_requests WHERE id = ?");
        $stmt->execute([$request_id]);
        return $stmt->fetch() ?: null;
    } catch (PDOException $e) {
        if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error finding pending request by ID {$request_id}: " . $e->getMessage() . "\n", FILE_APPEND); }
        return null;
    }
}

function updateAdminRequestMessages(int $request_id, ?string $original_caption, ?string $status_suffix): void {
    try {
        $messages = getPendingRequestMessages($request_id);
        $pdo = pdo();
        
        foreach ($messages as $msg) {
            $platform = $msg['platform'];
            $chat_id = $msg['chat_id'];
            $message_id = $msg['message_id'];

            $new_text = $original_caption ?? "درخواست پردازش شد";
            if ($status_suffix) {
                $new_text .= $status_suffix;
            }

            $params = [
                'chat_id' => $chat_id,
                'message_id' => $message_id,
                'reply_markup' => json_encode(['inline_keyboard' => []])
            ];
            
            $is_photo_message = false; 
            
            if ($is_photo_message) {
                $params['caption'] = $new_text;
                @apiRequest('editMessageCaption', $params, $platform);
            } else {
                 $params['text'] = $new_text;
                @apiRequest('editMessageText', $params, $platform);
            }
            
            $stmt_delete = $pdo->prepare("DELETE FROM admin_request_messages WHERE id = ?");
            @$stmt_delete->execute([$msg['id']]);
            
            usleep(50000);
        }
    } catch (Exception $e) {
        if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - Error updating admin request messages for request {$request_id}: " . $e->getMessage() . "\n", FILE_APPEND); }
    }
}
?>