<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once '../config/database.php';

try {
    $pdo = getDBConnection();
    
    // Get filters from POST data
    $input = json_decode(file_get_contents('php://input'), true);
    $filters = $input ?: [];
    
    // Build WHERE clause based on filters
    $whereConditions = [];
    $params = [];
    
    // Date range filter
    if (!empty($filters['dateFrom'])) {
        $whereConditions[] = "DATE(p.created_at) >= :date_from";
        $params[':date_from'] = $filters['dateFrom'];
    }
    
    if (!empty($filters['dateTo'])) {
        $whereConditions[] = "DATE(p.created_at) <= :date_to";
        $params[':date_to'] = $filters['dateTo'];
    }
    
    // Status filter
    if (!empty($filters['status'])) {
        $whereConditions[] = "p.status = :status";
        $params[':status'] = $filters['status'];
    }
    
    // Payment method filter
    if (!empty($filters['paymentMethod'])) {
        $whereConditions[] = "p.payment_method = :payment_method";
        $params[':payment_method'] = $filters['paymentMethod'];
    }
    
    // Amount range filters
    if (!empty($filters['amountMin'])) {
        $whereConditions[] = "p.amount >= :amount_min";
        $params[':amount_min'] = $filters['amountMin'];
    }
    
    if (!empty($filters['amountMax'])) {
        $whereConditions[] = "p.amount <= :amount_max";
        $params[':amount_max'] = $filters['amountMax'];
    }
    
    $whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';
    
    // Check if payments table exists
    $tableCheck = $pdo->query("SHOW TABLES LIKE 'payments'");
    $tableExists = $tableCheck->fetch();
    
    if (!$tableExists) {
        // Create payments table if it doesn't exist
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS payments (
                id INT AUTO_INCREMENT PRIMARY KEY,
                transaction_id VARCHAR(255) UNIQUE NOT NULL,
                appointment_id INT,
                amount DECIMAL(10,2) DEFAULT 0.00,
                status ENUM('PENDING', 'SUCCESS', 'FAILED', 'CANCELLED') DEFAULT 'PENDING',
                payment_method VARCHAR(50) DEFAULT 'PHONEPE',
                payment_id VARCHAR(255) NULL,
                phonepe_response TEXT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                INDEX idx_transaction_id (transaction_id),
                INDEX idx_appointment_id (appointment_id),
                INDEX idx_status (status)
            )
        ");
    }
    
    // Get payment statistics
    $statsQuery = "
        SELECT 
            COALESCE(SUM(CASE WHEN p.status = 'SUCCESS' THEN p.amount ELSE 0 END), 0) as total_revenue,
            COALESCE(SUM(CASE WHEN p.status = 'SUCCESS' AND DATE(p.created_at) = CURDATE() THEN p.amount ELSE 0 END), 0) as today_revenue,
            COUNT(CASE WHEN p.status = 'PENDING' THEN 1 END) as pending_payments,
            COUNT(CASE WHEN p.status = 'SUCCESS' THEN 1 END) as successful_payments
        FROM payments p
        $whereClause
    ";
    
    $statsStmt = $pdo->prepare($statsQuery);
    $statsStmt->execute($params);
    $stats = $statsStmt->fetch(PDO::FETCH_ASSOC);
    
    // Get payments with user details
    $paymentsQuery = "
        SELECT 
            p.id,
            p.transaction_id,
            p.amount,
            p.status,
            p.payment_method,
            p.created_at,
            p.phonepe_response,
            p.appointment_id,
            a.user_name,
            a.user_mobile
        FROM payments p
        LEFT JOIN appointments a ON p.appointment_id = a.id
        $whereClause
        ORDER BY p.created_at DESC
        LIMIT 100
    ";
    
    $paymentsStmt = $pdo->prepare($paymentsQuery);
    $paymentsStmt->execute($params);
    $payments = $paymentsStmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format the response
    $response = [
        'success' => true,
        'stats' => [
            'total_revenue' => (float)$stats['total_revenue'],
            'today_revenue' => (float)$stats['today_revenue'],
            'pending_payments' => (int)$stats['pending_payments'],
            'successful_payments' => (int)$stats['successful_payments']
        ],
        'payments' => $payments,
        'filters_applied' => $filters
    ];
    
    echo json_encode($response);
    
} catch (Exception $e) {
    error_log("Payments data error: " . $e->getMessage());
    
    $response = [
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage(),
        'stats' => [
            'total_revenue' => 0,
            'today_revenue' => 0,
            'pending_payments' => 0,
            'successful_payments' => 0
        ],
        'payments' => []
    ];
    
    echo json_encode($response);
}
?>
