<?php
header('Content-Type: application/json');
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

$response = [
    'success' => false,
    'message' => '',
    'event' => null,
    'agendas' => [],
    'sponsors' => [],
    'speakers' => [],
    'registrations' => [],
    'is_registered' => false,
    'all_sponsors' => [],
    'all_speakers' => [],
    'razorpay_key' => '',
    'role' => 'user'
];

if (!isLoggedIn()) {
    $response['message'] = "Unauthorized.";
    echo json_encode($response);
    exit();
}

$currentUser = getCurrentUser();
$response['role'] = $currentUser['role'];

$eventId = isset($_GET['event_id']) ? (int)$_GET['event_id'] : (isset($_POST['event_id']) ? (int)$_POST['event_id'] : 0);

if ($eventId <= 0) {
    $response['message'] = "Invalid Event ID.";
    echo json_encode($response);
    exit();
}

$allowedIds = getAccessibleEventIdsForUser($currentUser['id'], $currentUser['role'], $pdo);
if ($allowedIds !== null && !in_array($eventId, $allowedIds)) {
    $response['message'] = "Access Denied: This event is not permitted under your designation level.";
    echo json_encode($response);
    exit();
}

// Fetch Razorpay key
try {
    $response['razorpay_key'] = $pdo->query("SELECT value FROM system_settings WHERE key = 'razorpay_key_id'")->fetchColumn() ?: '';
    $response['all_sponsors'] = $pdo->query("SELECT id, company_name FROM sponsor_profiles ORDER BY company_name ASC")->fetchAll(PDO::FETCH_ASSOC) ?: [];
    $response['all_speakers'] = $pdo->query("SELECT id, full_name FROM speaker_profiles ORDER BY full_name ASC")->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (PDOException $e) { }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $response['message'] = "Security check failed (CSRF).";
        echo json_encode($response);
        exit();
    }

    $action = $_POST['action'] ?? '';

    try {
        $pdo->beginTransaction();
        
        // Fetch event details locked
        $stmt_lock = $pdo->prepare("SELECT * FROM events WHERE id = ? FOR UPDATE");
        $stmt_lock->execute([$eventId]);
        $event = $stmt_lock->fetch(PDO::FETCH_ASSOC);

        if (!$event) {
            $pdo->rollBack();
            $response['message'] = "Event not found.";
            echo json_encode($response);
            exit();
        }

        if (isset($event['status']) && $event['status'] === 'draft') {
            if ($currentUser['role'] !== 'admin' && $currentUser['role'] !== 'organizer') {
                $pdo->rollBack();
                $response['message'] = "Event not found.";
                echo json_encode($response);
                exit();
            }
        }

        if ($action === 'register') {
            // Check if already registered or waitlisted
            $check = $pdo->prepare("SELECT status FROM registrations WHERE event_id = ? AND user_id = ?");
            $check->execute([$eventId, $currentUser['id']]);
            $existing_reg_status = $check->fetchColumn();

            if ($existing_reg_status !== false) {
                $pdo->rollBack();
                if ($existing_reg_status === 'waitlisted') {
                    $response['message'] = "You are already on the waitlist for this event.";
                } else {
                    $response['message'] = "You are already registered for this event.";
                }
                echo json_encode($response);
                exit();
            }

            // Check capacity
            $check_cap = $pdo->prepare("SELECT COUNT(*) FROM registrations WHERE event_id = ? AND status = 'registered'");
            $check_cap->execute([$eventId]);
            $count = (int)$check_cap->fetchColumn();

            $is_waitlist = ($event['capacity'] > 0 && $count >= $event['capacity']);

            $ticket_price = $is_waitlist ? 0.00 : (float)$event['price'];
            // GST rate read from system_settings (configurable, fallback 18%)
            $stmt_gst = $pdo->query("SELECT value FROM system_settings WHERE key = 'gst_rate'");
            $gst_percent = (float)(($stmt_gst ? $stmt_gst->fetchColumn() : false) ?: 18.00);
            $gst_rate = $gst_percent / 100.00;
            $base_price = 0.00;
            $gst_amount = 0.00;
            $total_payable = 0.00;

            if ($ticket_price > 0.00) {
                if (($event['gst_option'] ?? 'excluding') === 'including') {
                    $total_payable = $ticket_price;
                    $base_price = $total_payable / (1.00 + $gst_rate);
                    $gst_amount = $total_payable - $base_price;
                } else {
                    $base_price = $ticket_price;
                    $gst_amount = $base_price * $gst_rate;
                    $total_payable = $base_price + $gst_amount;
                }
            }

            $payment_method = $_POST['payment_method'] ?? 'razorpay';
            $payment_id_val = $is_waitlist ? 'waitlist' : ($_POST['razorpay_payment_id'] ?? null);

            // Handle wallet payment deduction if selected
            if ($total_payable > 0 && !$is_waitlist && $payment_method === 'wallet') {
                // Fetch designation allow_wallet_payment flag
                $stmt_desig = $pdo->prepare("SELECT d.allow_wallet_payment FROM designations d JOIN users u ON u.designation_id = d.id WHERE u.id = ?");
                $stmt_desig->execute([$currentUser['id']]);
                $allow_wallet = $stmt_desig->fetchColumn();

                if (!$allow_wallet) {
                    $pdo->rollBack();
                    $response['message'] = "Your current designation does not allow wallet payments.";
                    echo json_encode($response);
                    exit();
                }

                // Check Wallet Balance
                $stmt_earn = $pdo->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM earnings WHERE user_id = ?");
                $stmt_earn->execute([$currentUser['id']]);
                $total_earnings = (float)$stmt_earn->fetchColumn();

                $stmt_pay = $pdo->prepare("SELECT COALESCE(SUM(amount), 0.00) FROM payouts WHERE user_id = ? AND status IN ('pending', 'paid')");
                $stmt_pay->execute([$currentUser['id']]);
                $total_withdrawn = (float)$stmt_pay->fetchColumn();

                $available_balance = max(0.00, $total_earnings - $total_withdrawn);

                if ($available_balance < $total_payable) {
                    $pdo->rollBack();
                    $response['message'] = "Insufficient wallet balance. You need ₹" . number_format($total_payable, 2) . " but have ₹" . number_format($available_balance, 2);
                    echo json_encode($response);
                    exit();
                }

                // Deduct from wallet by inserting a paid payout record
                // platform_fee and tds_amount are 0 for wallet-to-event payments; net_amount = amount
                $stmt_ins_payout = $pdo->prepare("
                    INSERT INTO payouts (user_id, amount, platform_fee, tds_amount, net_amount, status, bank_name, account_number) 
                    VALUES (?, ?, 0.00, 0.00, ?, 'paid', 'Wallet Event Payment', ?)
                ");
                $stmt_ins_payout->execute([$currentUser['id'], $total_payable, $total_payable, 'Event#' . $eventId]);
                
                $payment_id_val = 'wallet_pay_' . time() . '_' . rand(100, 999);
            }

            $register = $pdo->prepare("INSERT INTO registrations (event_id, user_id, base_price, gst_rate, gst_amount, total_payable, razorpay_payment_id, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $status_val = $is_waitlist ? 'waitlisted' : 'registered';
            $register->execute([$eventId, $currentUser['id'], $base_price, $gst_percent, $gst_amount, $total_payable, $payment_id_val, $status_val]);

            // Dispatch notification
            require_once __DIR__ . '/../../includes/notification_helper.php';
            sendMultichannelNotification($currentUser['id'], $is_waitlist ? 'waitlist_entry' : 'event_registration', [
                'event_title' => $event['title'],
                'location' => $event['location'],
                'start_date' => date('Y-m-d H:i', strtotime($event['start_date']))
            ]);

            // Distribute Level-Based Commissions via single recursive CTE (avoids N+1 query per parent)
            if ($ticket_price > 0.00 && !$is_waitlist) {
                try {
                    $stmt_chain = $pdo->prepare("
                        WITH RECURSIVE parent_chain AS (
                            SELECT u.parent_id AS uid, 1 AS level
                            FROM users u WHERE u.id = ?
                            UNION ALL
                            SELECT u.parent_id, p.level + 1
                            FROM users u
                            INNER JOIN parent_chain p ON u.id = p.uid
                            WHERE p.level < 5 AND p.uid IS NOT NULL
                        )
                        SELECT
                            pc.uid AS parent_id,
                            pc.level,
                            d.matrix_depth,
                            d.level_commissions,
                            d.criteria_max_earning_cap,
                            COALESCE(SUM(e.amount), 0.00) AS monthly_earned
                        FROM parent_chain pc
                        JOIN users u ON u.id = pc.uid
                        LEFT JOIN designations d ON u.designation_id = d.id
                        LEFT JOIN earnings e ON e.user_id = pc.uid
                            AND e.created_at >= date_trunc('month', CURRENT_TIMESTAMP)
                        WHERE pc.uid IS NOT NULL
                        GROUP BY pc.uid, pc.level, d.matrix_depth, d.level_commissions, d.criteria_max_earning_cap
                        ORDER BY pc.level ASC
                    ");
                    $stmt_chain->execute([$currentUser['id']]);
                    $parent_rows = $stmt_chain->fetchAll(PDO::FETCH_ASSOC);
                } catch (PDOException $e) {
                    $parent_rows = [];
                }

                if (!empty($parent_rows)) {
                    $stmt_earn = $pdo->prepare("
                        INSERT INTO earnings (user_id, buyer_id, event_id, amount, level, percentage)
                        VALUES (?, ?, ?, ?, ?, ?)
                    ");
                    foreach ($parent_rows as $p) {
                        $depth = (int)($p['matrix_depth'] ?? 0);
                        $level = (int)$p['level'];
                        $commissions_arr = array_values(array_filter(array_map('trim', explode(',', $p['level_commissions'] ?? ''))));
                        if ($level <= $depth && isset($commissions_arr[$level - 1])) {
                            $pct = (float)$commissions_arr[$level - 1];
                            if ($pct > 0) {
                                $earn_amount = $base_price * ($pct / 100.00);
                                // Enforce monthly cap
                                $monthly_cap = (float)($p['criteria_max_earning_cap'] ?? 0.00);
                                if ($monthly_cap > 0.00) {
                                    $monthly_earned = (float)$p['monthly_earned'];
                                    if ($monthly_earned >= $monthly_cap) {
                                        $earn_amount = 0.00;
                                    } else {
                                        $earn_amount = min($earn_amount, $monthly_cap - $monthly_earned);
                                    }
                                }
                                if ($earn_amount > 0.00) {
                                    $stmt_earn->execute([$p['parent_id'], $currentUser['id'], $eventId, $earn_amount, $level, $pct]);
                                }
                            }
                        }
                    }
                }
            }

            $pdo->commit();
            $response['success'] = true;
            $response['message'] = $is_waitlist ? "Event is currently full. You have successfully joined the waitlist!" : "You have registered successfully!";
        } elseif ($action === 'add_agenda') {
            $topic = trim($_POST['topic'] ?? '');
            $agenda_date = trim($_POST['agenda_date'] ?? '');
            $start_time = trim($_POST['start_time'] ?? '');
            $end_time = trim($_POST['end_time'] ?? '');
            $sp_id = !empty($_POST['speaker_profile_id']) ? (int)$_POST['speaker_profile_id'] : null;
            $sp_name = trim($_POST['speaker'] ?? '');

            $stmt = $pdo->prepare("
                INSERT INTO event_agendas (event_id, speaker_profile_id, agenda_date, start_time, end_time, title, speaker, description) 
                VALUES (?, ?, ?, ?, ?, ?, ?, '')
            ");
            $stmt->execute([$eventId, $sp_id, $agenda_date, $start_time, $end_time, $topic, $sp_name]);
            $response['success'] = true;
            $response['message'] = "Agenda topic added successfully.";
        } elseif ($action === 'delete_agenda') {
            $agenda_id = (int)$_POST['agenda_id'];
            $stmt = $pdo->prepare("DELETE FROM event_agendas WHERE id = ? AND event_id = ?");
            $stmt->execute([$agenda_id, $eventId]);
            $response['success'] = true;
            $response['message'] = "Agenda topic removed.";
        } elseif ($action === 'link_speaker') {
            $sp_id = (int)$_POST['speaker_profile_id'];
            $stmt = $pdo->prepare("INSERT INTO event_speakers (event_id, speaker_profile_id) VALUES (?, ?)");
            $stmt->execute([$eventId, $sp_id]);
            $response['success'] = true;
            $response['message'] = "Speaker linked.";
        } elseif ($action === 'link_sponsor') {
            $sp_id = (int)$_POST['sponsor_profile_id'];
            $tier = $_POST['tier'] ?? 'Bronze';
            $stmt = $pdo->prepare("INSERT INTO event_sponsors (event_id, sponsor_profile_id, tier) VALUES (?, ?, ?)");
            $stmt->execute([$eventId, $sp_id, $tier]);
            $response['success'] = true;
            $response['message'] = "Sponsor linked.";
        } elseif ($action === 'unlink_speaker') {
            $sp_id = (int)$_POST['speaker_profile_id'];
            $stmt = $pdo->prepare("DELETE FROM event_speakers WHERE event_id = ? AND speaker_profile_id = ?");
            $stmt->execute([$eventId, $sp_id]);
            $response['success'] = true;
            $response['message'] = "Speaker unlinked.";
        } elseif ($action === 'unlink_sponsor') {
            $sp_id = (int)$_POST['sponsor_profile_id'];
            $stmt = $pdo->prepare("DELETE FROM event_sponsors WHERE event_id = ? AND sponsor_profile_id = ?");
            $stmt->execute([$eventId, $sp_id]);
            $response['success'] = true;
            $response['message'] = "Sponsor unlinked.";
        } elseif ($action === 'cancel_registration') {
            // Cancel the current user's registration and promote first waitlisted user
            $stmt_reg = $pdo->prepare("SELECT id, status FROM registrations WHERE event_id = ? AND user_id = ?");
            $stmt_reg->execute([$eventId, $currentUser['id']]);
            $my_reg = $stmt_reg->fetch(PDO::FETCH_ASSOC);

            if (!$my_reg) {
                $pdo->rollBack();
                $response['message'] = "You are not registered for this event.";
                echo json_encode($response);
                exit();
            }

            // Remove the registration
            $pdo->prepare("DELETE FROM registrations WHERE id = ?")->execute([$my_reg['id']]);

            // If it was a confirmed registration and event has capacity, promote first waitlisted user
            if ($my_reg['status'] === 'registered' && $event['capacity'] > 0) {
                $stmt_wl = $pdo->prepare("
                    SELECT r.id, r.user_id FROM registrations r
                    WHERE r.event_id = ? AND r.status = 'waitlisted'
                    ORDER BY r.id ASC LIMIT 1
                ");
                $stmt_wl->execute([$eventId]);
                $next = $stmt_wl->fetch(PDO::FETCH_ASSOC);
                if ($next) {
                    $pdo->prepare("UPDATE registrations SET status = 'registered' WHERE id = ?")->execute([$next['id']]);
                    require_once __DIR__ . '/../../includes/notification_helper.php';
                    sendMultichannelNotification($next['user_id'], 'event_registration', [
                        'event_title' => $event['title'],
                        'location'    => $event['location'],
                        'start_date'  => date('Y-m-d H:i', strtotime($event['start_date']))
                    ]);
                }
            }

            $pdo->commit();
            $response['success'] = true;
            $response['message'] = "Your registration has been cancelled.";
        }
    } catch (PDOException $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        error_log("event_detail_member action error: " . $e->getMessage());
        $response['message'] = "Action failed. Please try again.";
    }
} else {
    // GET requests
    try {
        // Fetch Event details
        $stmt = $pdo->prepare("SELECT * FROM events WHERE id = ?");
        $stmt->execute([$eventId]);
        $response['event'] = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$response['event']) {
            $response['message'] = "Event not found.";
            echo json_encode($response);
            exit();
        }

        if (isset($response['event']['status']) && $response['event']['status'] === 'draft') {
            if ($currentUser['role'] !== 'admin' && $currentUser['role'] !== 'organizer') {
                $response['message'] = "Event not found.";
                echo json_encode($response);
                exit();
            }
        }

        // Fetch Agendas
        $stmt_ag = $pdo->prepare("
            SELECT ea.*, sp.full_name as speaker_name 
            FROM event_agendas ea 
            LEFT JOIN speaker_profiles sp ON ea.speaker_profile_id = sp.id 
            WHERE ea.event_id = ? 
            ORDER BY ea.agenda_date ASC, ea.start_time ASC
        ");
        $stmt_ag->execute([$eventId]);
        $response['agendas'] = $stmt_ag->fetchAll(PDO::FETCH_ASSOC) ?: [];

        // Fetch linked sponsors
        $stmt_sp = $pdo->prepare("
            SELECT es.*, sp.company_name, sp.website_url 
            FROM event_sponsors es 
            JOIN sponsor_profiles sp ON es.sponsor_profile_id = sp.id 
            WHERE es.event_id = ?
        ");
        $stmt_sp->execute([$eventId]);
        $response['sponsors'] = $stmt_sp->fetchAll(PDO::FETCH_ASSOC) ?: [];

        // Fetch linked speakers
        $stmt_spk = $pdo->prepare("
            SELECT esk.*, sp.full_name, sp.expertise 
            FROM event_speakers esk 
            JOIN speaker_profiles sp ON esk.speaker_profile_id = sp.id 
            WHERE esk.event_id = ?
        ");
        $stmt_spk->execute([$eventId]);
        $response['speakers'] = $stmt_spk->fetchAll(PDO::FETCH_ASSOC) ?: [];

        // Fetch attendee registrations
        $stmt_reg = $pdo->prepare("
            SELECT r.*, u.username, u.email 
            FROM registrations r 
            JOIN users u ON r.user_id = u.id 
            WHERE r.event_id = ? 
            ORDER BY r.id DESC
        ");
        $stmt_reg->execute([$eventId]);
        $response['registrations'] = $stmt_reg->fetchAll(PDO::FETCH_ASSOC) ?: [];

        // Check if current user is registered
        $stmt_check = $pdo->prepare("SELECT COUNT(*) FROM registrations WHERE event_id = ? AND user_id = ?");
        $stmt_check->execute([$eventId, $currentUser['id']]);
        $response['is_registered'] = $stmt_check->fetchColumn() > 0;

        $response['success'] = true;
    } catch (PDOException $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $response['message'] = "Action failed.";
        echo json_encode($response);
    }
}

echo json_encode($response);
