<?php

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

function getUnpaidPartnerProfit(int $partner_user_id, bool $only_withdrawable = false): string {
    try {
        $sql = "
            SELECT SUM(o.total_partner_profit)
            FROM orders o
            JOIN users u ON o.user_id = u.id
            WHERE u.referred_by_user_id = :partner_user_id
              AND o.total_partner_profit > 0
              AND o.is_profit_paid = FALSE
              AND o.payout_request_id IS NULL
              AND o.status IN ('completed', 'shipped', 'processing')
        ";

        if ($only_withdrawable) {
            $sql .= " AND o.created_at < NOW() - INTERVAL 7 DAY";
        }
            
        $stmt = pdo()->prepare($sql);
        $stmt->execute([':partner_user_id' => $partner_user_id]);
        return $stmt->fetchColumn() ?: '0.00';
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB 
Error getting unpaid partner profit for {$partner_user_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return '0.00';
    }
}

function getPendingPayoutRequest(int $partner_user_id): ?array {
    try {
        $stmt = pdo()->prepare("SELECT * FROM payout_requests WHERE partner_user_id = ? AND status = 'pending' LIMIT 1");
        
      $stmt->execute([$partner_user_id]);
        return $stmt->fetch() ?: null;
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error getting pending 
payout request for {$partner_user_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return null;
    }
}

function createPayoutRequest(int $partner_user_id, string $amount, int $user_card_id): int {
    $pdo = pdo();
    try {
        $pdo->beginTransaction();
        
        $stmt = $pdo->prepare("
            INSERT INTO payout_requests (partner_user_id, amount, user_card_id, status, created_at)
            VALUES (?, ?, ?, 'pending', NOW())
        ");
        $stmt->execute([$partner_user_id, $amount, $user_card_id]);
        $payout_request_id = (int)$pdo->lastInsertId();

        if ($payout_request_id > 0) {
            $stmt_link = $pdo->prepare("
                UPDATE orders o
                JOIN users u ON o.user_id = u.id
                SET o.payout_request_id = :payout_request_id
                WHERE u.referred_by_user_id = :partner_user_id
                  AND o.total_partner_profit > 0
                  AND o.is_profit_paid = FALSE
                  AND o.payout_request_id IS NULL
                  AND o.status IN ('completed', 'shipped', 'processing')
                  AND o.created_at < NOW() - INTERVAL 7 DAY
            ");
        
            $stmt_link->execute([
                ':payout_request_id' => $payout_request_id,
                ':partner_user_id' => $partner_user_id
            ]);
        }
        
        $pdo->commit();
        return $payout_request_id;
    } catch (Exception $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error creating payout request for {$partner_user_id}: " . $e->getMessage() . "\n", FILE_APPEND);
 
        return 0;
    }
}

function getPartnerOrders(int $user_id, int $limit, int $offset, bool $only_self_orders): array {
    try {
        $sql = "SELECT o.*, u.first_name 
                FROM orders o 
                JOIN users u ON o.user_id = u.id 
                WHERE ";
        
         if ($only_self_orders) {
            $sql .= " o.user_id = :user_id";
            
$params = [':user_id' => $user_id];
        } else {
            $sql .= " u.referred_by_user_id = :user_id";
            $params = [':user_id' => $user_id];
         }
        
        $sql .= " AND o.order_type = 'product' 
                  ORDER BY o.created_at DESC 
                  LIMIT :limit OFFSET :offset";
        
        $stmt = pdo()->prepare($sql);
        $stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
       
         $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error getting partner orders (self: {$only_self_orders}) for user {$user_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return 
[];
    }
}

function countPartnerOrders(int $user_id, bool $only_self_orders): int {
    try {
         $sql = "SELECT COUNT(o.id) 
                FROM orders o 
                
  JOIN users u ON o.user_id = u.id 
                WHERE ";
        
        if ($only_self_orders) {
            $sql .= " o.user_id = :user_id";
        } else {
        
            $sql .= " u.referred_by_user_id = :user_id";
        }
        
      
  $sql .= " AND o.order_type = 'product'";
        
        $stmt = pdo()->prepare($sql);
        $stmt->execute([':user_id' => $user_id]);

        return (int)$stmt->fetchColumn();
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error counting partner orders (self: {$only_self_orders}) for 
user {$user_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return 0;
    }
}

function getPayoutRequestDetails(int $payout_request_id): ?array {
   try {
        $stmt = pdo()->prepare("
            SELECT pr.*, u.first_name, u.phone_number, uc.card_number_masked
                 FROM payout_requests pr
            JOIN users u ON pr.partner_user_id = u.id
            JOIN user_cards uc ON pr.user_card_id = uc.id
            WHERE pr.id = ?
        ");
        $stmt->execute([$payout_request_id]);
        return $stmt->fetch() ?: null;
    } catch (PDOException $e) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error getting payout request details for {$payout_request_id}: " . $e->getMessage() . "\n", FILE_APPEND);
 
        return null;
    }
}

function getPendingPayoutRequests(int $offset, int $limit): array {
    try {
        $stmt = pdo()->prepare("
            SELECT pr.*, u.first_name, u.phone_number
            
              FROM payout_requests pr
            JOIN users u ON pr.partner_user_id = u.id
            WHERE pr.status = 'pending'
            ORDER BY pr.created_at ASC
            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) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error getting pending payout requests: " . $e->getMessage() . "\n", FILE_APPEND);
       
         return [];
    }
}

function countPendingPayoutRequests(): int {
    try {
        return (int)pdo()->query("SELECT COUNT(*) FROM payout_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 
payout requests: " . $e->getMessage() . "\n", FILE_APPEND); }
        return 0;
    }
}

function completePayoutRequest(int $payout_request_id, int $admin_user_id): bool {
    $pdo = pdo();
    try {
        $pdo->beginTransaction();
  
        
        $stmt_req = $pdo->prepare("
            UPDATE payout_requests 
            SET status = 'completed', processed_at = NOW(), processed_by_admin_id = ?
            WHERE id = ? AND status = 'pending'
        ");
  
      $stmt_req->execute([$admin_user_id, $payout_request_id]);
        
        
if ($stmt_req->rowCount() == 0) {
            throw new Exception("Payout request {$payout_request_id} not found or already processed.");
        }

        $stmt_orders = $pdo->prepare("
             UPDATE orders
            SET is_profit_paid = TRUE
            WHERE payout_request_id = ?
        ");
        $stmt_orders->execute([$payout_request_id]);
        
        $pdo->commit();
        return true;
    } catch (Exception $e) {
        if ($pdo->inTransaction()) {

            $pdo->rollBack();
        }
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error completing payout request {$payout_request_id}: " . $e->getMessage() . "\n", FILE_APPEND);
  
      return false;
    }
}

function rejectPayoutRequest(int $payout_request_id, int $admin_user_id, string $admin_notes): bool {
    $pdo = pdo();
    try {
        $pdo->beginTransaction();

        $stmt_req = $pdo->prepare("
            UPDATE payout_requests 
            SET status = 'rejected', processed_at = NOW(), processed_by_admin_id = ?, admin_notes = ?
            WHERE id = ? AND status = 'pending'
        ");
        
        $stmt_req->execute([$admin_user_id, $admin_notes, $payout_request_id]);
        
        if ($stmt_req->rowCount() == 0) {
            throw new Exception("Payout request {$payout_request_id} not found or already processed.");
        }

        $stmt_orders = $pdo->prepare("
             UPDATE orders
             SET payout_request_id = NULL
             WHERE payout_request_id = ?
        ");
        $stmt_orders->execute([$payout_request_id]);
        
        $pdo->commit();
        return true;
    } catch (Exception $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error rejecting payout request {$payout_request_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return false;
    }
}


function storePayoutRequestMessage(int $payout_request_id, int $admin_user_id, string $platform, int $chat_id, int $message_id): bool {
    try {
        $stmt = pdo()->prepare("INSERT INTO payout_request_messages (payout_request_id, admin_user_id, platform, chat_id, message_id) VALUES (?, ?, ?, ?, ?)");
        return $stmt->execute([$payout_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 payout request message: " . $e->getMessage() . "\n", FILE_APPEND); }
      return false;
    }
}

function getPayoutRequestMessages(int $payout_request_id): array {
    try {
 
       $stmt = pdo()->prepare("SELECT * FROM payout_request_messages WHERE payout_request_id = ?");
        $stmt->execute([$payout_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 payout request messages for request {$payout_request_id}: " . $e->getMessage() . "\n", FILE_APPEND); }
        return 
[];
    }
}

function deletePayoutRequestMessages(int $payout_request_id): void {
    try {
        $messages = getPayoutRequestMessages($payout_request_id);
        $pdo = pdo();
        
        foreach ($messages as $msg) {
            $text = "این درخواست قبلاً پردازش شده است.";
            $platform = $msg['platform'];
            $chat_id = $msg['chat_id'];
            $message_id = $msg['message_id'];
            
            $params = [
                'chat_id' => $chat_id,
                'message_id' => $message_id,
                'text' => $text,
                'reply_markup' => json_encode(['inline_keyboard' => []])
            ];
            
            @apiRequest('editMessageText', $params, $platform);
            
            $stmt_delete = $pdo->prepare("DELETE FROM payout_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 deleting payout request messages for request {$payout_request_id}: " . $e->getMessage() . "\n", FILE_APPEND); }
    }
}

?>