#!/bin/bash
# Combined fix script for venue sync issues
#
# Fixes:
# 1. Database migrations (includes FK constraint fixes)
# 2. event_venues links (events not linked to published templates)
# 3. Stale tier references (template JSON has old tier IDs)
#
# Usage: ./scripts/fix-venue-sync-issues.sh
#
# Safe to run multiple times - all fixes are idempotent.

set -e

SCRIPT_DIR="$(dirname "$0")"
cd "$SCRIPT_DIR/.."

echo "========================================"
echo "Venue Sync Issues Fix Script"
echo "========================================"
echo "Date: $(date)"
echo ""

# Detect PHP binary (cPanel uses different path)
if [ -f /opt/cpanel/ea-php81/root/usr/bin/php ]; then
    PHP_BIN="/opt/cpanel/ea-php81/root/usr/bin/php"
else
    PHP_BIN="php"
fi
echo "Using PHP: $PHP_BIN"
echo ""

# Step 0: Run migrations (includes FK constraint fix)
echo "=== Step 0: Running database migrations ==="
$PHP_BIN artisan migrate --force 2>&1 || {
    echo "WARNING: Migrations failed, continuing with other fixes..."
}
echo ""

# Step 1: Event-venue links
echo "=== Step 1: Fixing event_venues links ==="
source scripts/_db-helper.sh

# Check and fix event_venues
MISSING=$(db_query "
SELECT COUNT(*) as count
FROM events e
WHERE e.venue_id IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM event_venues ev WHERE ev.event_id = e.id);
" 2>/dev/null | tail -1)

if [[ -n "$MISSING" && "$MISSING" != "0" ]]; then
    echo "Found $MISSING events without event_venues links"

    # Auto-fix
    db_query "
    INSERT INTO event_venues (event_id, venue_template_id, is_active, created_at, updated_at)
    SELECT
        e.id as event_id,
        vt.id as venue_template_id,
        1 as is_active,
        NOW() as created_at,
        NOW() as updated_at
    FROM events e
    JOIN venue_templates vt ON vt.venue_id = e.venue_id AND vt.status = 'published'
    WHERE e.venue_id IS NOT NULL
    AND NOT EXISTS (SELECT 1 FROM event_venues ev WHERE ev.event_id = e.id);
    " 2>/dev/null

    echo "Fixed event_venues links"
else
    echo "No missing event_venues links found"
fi

echo ""

# Step 2: Stale tier references
echo "=== Step 2: Fixing stale tier references ==="
# Only fix published templates for venue 1 to avoid memory issues
PUBLISHED_TEMPLATES=$($PHP_BIN -r "
require 'vendor/autoload.php';
\$app = require 'bootstrap/app.php';
\$app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap();
\$templates = \App\Model\VenueTemplate::where('status', 'published')->pluck('id')->toArray();
echo implode(' ', \$templates);
" 2>/dev/null)

if [ -n "$PUBLISHED_TEMPLATES" ]; then
    for TEMPLATE_ID in $PUBLISHED_TEMPLATES; do
        echo "Processing template $TEMPLATE_ID..."
        $PHP_BIN -d memory_limit=512M scripts/fix-stale-tier-refs.php "$TEMPLATE_ID" 2>&1 || {
            echo "WARNING: Failed to fix template $TEMPLATE_ID, continuing..."
        }
    done
else
    echo "No published templates found to fix"
fi

echo ""
echo "========================================"
echo "All fixes complete!"
echo "========================================"
echo ""
echo "Verification commands:"
echo "  - Check event_venues: SELECT * FROM event_venues;"
echo "  - Check availability: curl /api/events/{slug}/availability | jq '.data[0]'"
echo "  - Test comp reservation from admin panel"
echo ""
