<?php

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

function createTransaction(int $order_id, string $authority, int $amount_rial): int {
    try {
        $stmt = pdo()->prepare(
            "INSERT INTO payment_transactions (order_id, authority, amount_rial, status, created_at, updated_at)
             VALUES (?, ?, ?, 'pending', NOW(), NOW())"
        );
        $stmt->execute([$order_id, $authority, $amount_rial]);
        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 transaction for order {$order_id} (Auth: {$authority}): " . $e->getMessage() . "\n", FILE_APPEND);
        }
        return 0;
    }
}

function updateTransactionStatus(string $authority, string $new_status, ?string $ref_id = null, ?string $card_pan = null): bool {
    try {
        $sql = "UPDATE payment_transactions SET status = ?, updated_at = NOW()";
        $params = [$new_status];

        if ($ref_id !== null) {
            $sql .= ", ref_id = ?";
            $params[] = $ref_id;
        }
        if ($card_pan !== null) {
            $sql .= ", card_pan_masked = ?";
            $params[] = $card_pan;
        }

        $sql .= " WHERE authority = ?";
        $params[] = $authority;

        $stmt = pdo()->prepare($sql);
        $updated = $stmt->execute($params);
        return $updated && $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 transaction status for authority {$authority} to {$new_status}: " . $e->getMessage() . "\n", FILE_APPEND);
        }
        return false;
    }
}


function getTransactionByAuthority(string $authority): ?array {
     try {
         $stmt = pdo()->prepare(
            // --- START FIX: Select o.order_type as well ---
             "SELECT pt.*, o.user_id, o.total_amount, o.status as order_status, o.order_type, u.telegram_chat_id, u.bale_chat_id, o.subtotal_amount, o.order_note
              FROM payment_transactions pt
              JOIN orders o ON pt.order_id = o.id
              JOIN users u ON o.user_id = u.id
              WHERE pt.authority = ?"
            // --- END FIX ---
         );
         $stmt->execute([$authority]);
         $transaction = $stmt->fetch();

         if ($transaction && isset($transaction['amount_rial'])) {
             $transaction['amount_toman'] = (int) floor($transaction['amount_rial'] / 10);
         }

         return $transaction ?: null;
     } catch (PDOException $e) {
         if (defined('ERROR_LOG_PATH')) {
             file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - DB Error getting transaction by authority ({$authority}): " . $e->getMessage() . "\n", FILE_APPEND);
         }
         return null;
     }
}

function getLastPendingTransactionForOrder(int $order_id): ?array {
    try {
      $stmt = pdo()->prepare(
            "SELECT * FROM payment_transactions
             WHERE order_id = ? AND status = 'pending'
             ORDER BY created_at DESC
             LIMIT 1"
        );
        $stmt->execute([$order_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 getting last pending transaction for order {$order_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        }
        return null;
    }
}

?>