#!/bin/bash

# Load environment variables
source .env

# SSH credentials for Cloudways
SSH_HOST="${UPSKILL_STAGING_IP}"
SSH_USER="${UPSKILL_STAGING_SSH_USER}"
SSH_PASS="${UPSKILL_STAGING_PASS}"
SSH_PORT="22"
REMOTE_PATH="${UPSKILL_STAGING_PATH}"

echo "Deploying dashboard fix to staging..."
echo "Using SSH: ${SSH_USER}@${SSH_HOST}:${SSH_PORT}"

# Create the fixed dashboard data class content
FIXED_CONTENT='<?php
/**
 * Dashboard data handler (fixed version)
 */
class HVAC_Dashboard_Data {
    
    /**
     * The user ID to fetch data for
     *
     * @var int
     */
    private $user_id;
    
    /**
     * Constructor
     *
     * @param int $user_id User ID to fetch data for
     */
    public function __construct( $user_id = null ) {
        $this->user_id = $user_id ?: get_current_user_id();
    }
    
    /**
     * Get total events count
     *
     * @return int
     */
    public function get_total_events_count() : int {
        $args = array(
            "post_type"      => Tribe__Events__Main::POSTTYPE,
            "author"         => $this->user_id,
            "post_status"    => array( "publish", "future" ),
            "posts_per_page" => -1,
            "fields"         => "ids",
        );
        
        $query = new WP_Query( $args );
        
        return (int) $query->found_posts;
    }
    
    /**
     * Get upcoming events count
     *
     * @return int
     */
    public function get_upcoming_events_count() : int {
        $today = current_time( "mysql" );
        $args  = array(
            "post_type"      => Tribe__Events__Main::POSTTYPE,
            "author"         => $this->user_id,
            "post_status"    => array( "publish", "future" ),
            "posts_per_page" => -1,
            "fields"         => "ids",
            "meta_query"     => array(
                array(
                    "key"     => "_EventStartDate",
                    "value"   => $today,
                    "compare" => ">=",
                    "type"    => "DATETIME",
                ),
            ),
        );
        
        $query = new WP_Query( $args );
        
        return (int) $query->found_posts;
    }
    
    /**
     * Get past events count
     *
     * @return int
     */
    public function get_past_events_count() : int {
        $today = current_time( "mysql" );
        $args  = array(
            "post_type"      => Tribe__Events__Main::POSTTYPE,
            "author"         => $this->user_id,
            "post_status"    => array( "publish", "future" ),
            "posts_per_page" => -1,
            "fields"         => "ids",
            "meta_query"     => array(
                array(
                    "key"     => "_EventEndDate",
                    "value"   => $today,
                    "compare" => "<",
                    "type"    => "DATETIME",
                ),
            ),
        );
        
        $query = new WP_Query( $args );
        
        return (int) $query->found_posts;
    }
    
    /**
     * Get total tickets sold
     *
     * @return int
     */
    public function get_total_tickets_sold() : int {
        $events = $this->get_user_events();
        $total  = 0;
        
        foreach ( $events as $event_id ) {
            $tickets = Tribe__Tickets__Tickets::get_event_tickets( $event_id );
            
            foreach ( $tickets as $ticket ) {
                $total += absint( $ticket->qty_sold() );
            }
        }
        
        return $total;
    }
    
    /**
     * Get total revenue
     *
     * @return float
     */
    public function get_total_revenue() : float {
        $events = $this->get_user_events();
        $total  = 0.0;
        
        foreach ( $events as $event_id ) {
            $tickets = Tribe__Tickets__Tickets::get_event_tickets( $event_id );
            
            foreach ( $tickets as $ticket ) {
                $total += floatval( $ticket->price ) * absint( $ticket->qty_sold() );
            }
        }
        
        return $total;
    }
    
    /**
     * Get all event IDs for a user
     *
     * @return array
     */
    private function get_user_events() : array {
        $args = array(
            "post_type"      => Tribe__Events__Main::POSTTYPE,
            "author"         => $this->user_id,
            "post_status"    => array( "publish", "future" ),
            "posts_per_page" => -1,
            "fields"         => "ids",
        );
        
        $query = new WP_Query( $args );
        
        return $query->posts;
    }
    
    /**
     * Get upcoming events
     *
     * @param int $limit Number of events to return
     * @return array
     */
    public function get_upcoming_events( $limit = 5 ) : array {
        $today = current_time( "mysql" );
        $args  = array(
            "post_type"      => Tribe__Events__Main::POSTTYPE,
            "author"         => $this->user_id,
            "post_status"    => array( "publish", "future" ),
            "posts_per_page" => $limit,
            "meta_key"       => "_EventStartDate",
            "orderby"        => "meta_value",
            "order"          => "ASC",
            "meta_query"     => array(
                array(
                    "key"     => "_EventStartDate",
                    "value"   => $today,
                    "compare" => ">=",
                    "type"    => "DATETIME",
                ),
            ),
        );
        
        $query = new WP_Query( $args );
        
        return $query->posts;
    }
}
?>'

echo "Creating fixed file on staging server..."

# Use sshpass to connect and deploy
sshpass -p "${SSH_PASS}" ssh -o StrictHostKeyChecking=no "${SSH_USER}@${SSH_HOST}" -p ${SSH_PORT} << EOF
cd ${REMOTE_PATH}

# Create the fixed file
echo '${FIXED_CONTENT}' > wp-content/plugins/hvac-community-events/includes/class-hvac-dashboard-data-fixed.php

# Backup the original
cp wp-content/plugins/hvac-community-events/includes/class-hvac-dashboard-data.php \
   wp-content/plugins/hvac-community-events/includes/class-hvac-dashboard-data.backup.php

# Replace with fixed version
cp wp-content/plugins/hvac-community-events/includes/class-hvac-dashboard-data-fixed.php \
   wp-content/plugins/hvac-community-events/includes/class-hvac-dashboard-data.php

# Clear WordPress cache
wp cache flush --allow-root

echo "Dashboard fix deployed successfully"
EOF

echo "Testing the fix..."
sshpass -p "${SSH_PASS}" ssh -o StrictHostKeyChecking=no "${SSH_USER}@${SSH_HOST}" -p ${SSH_PORT} << 'EOF'
cd /home/974670.cloudwaysapps.com/uberrxmprk/public_html

wp eval '
$user_id = 17;
$dashboard_data = new HVAC_Dashboard_Data($user_id);
echo "User ID: " . $user_id . "\n";
echo "Total Events: " . $dashboard_data->get_total_events_count() . "\n";
echo "Upcoming Events: " . $dashboard_data->get_upcoming_events_count() . "\n";
echo "Past Events: " . $dashboard_data->get_past_events_count() . "\n";
echo "Total Tickets: " . $dashboard_data->get_total_tickets_sold() . "\n";
echo "Total Revenue: " . $dashboard_data->get_total_revenue() . "\n";

// Check the database directly
global $wpdb;
$events = $wpdb->get_results($wpdb->prepare(
    "SELECT ID, post_title, post_status FROM $wpdb->posts 
     WHERE post_type = %s AND post_author = %d",
    "tribe_events", $user_id
));

echo "\nEvents in table: " . count($events) . "\n";
foreach ($events as $event) {
    echo "  - " . $event->post_title . " (" . $event->post_status . ")\n";
}
' --allow-root
EOF

echo "Dashboard fix deployed. You should now see the correct stats at: ${UPSKILL_STAGING_URL}hvac-dashboard/"