<?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' => '',
    'events' => [],
    'speakers' => [],
    'total_pages' => 1,
    'page' => 1
];

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

$currentUser = getCurrentUser();
$role = $currentUser['role'];
$isAdmin = ($role === 'admin' || $role === 'organizer');

// Load Speaker profiles for agenda dropdown options
try {
    $response['speakers'] = $pdo->query("SELECT id, full_name, organization 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'] ?? '';

    if (isset($_POST['submit_add'])) {
        if (!$isAdmin) {
            $response['message'] = "Unauthorized action.";
            echo json_encode($response);
            exit();
        }

        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $start_date = trim($_POST['start_date'] ?? '');
        $end_date = trim($_POST['end_date'] ?? '');
        $banner_url = trim($_POST['banner_url'] ?? '');
        $event_type = $_POST['event_type'] ?? 'physical';
        $capacity = (int)($_POST['capacity'] ?? 0);
        $agenda_json = $_POST['agenda_json'] ?? '[]';
        $payment_type = trim($_POST['payment_type'] ?? 'free');
        $price = 0.00;
        $rzp_key_id = null;
        $rzp_key_secret = null;
        if ($payment_type === 'paid') {
            $price = (float)($_POST['price'] ?? 0.00);
            $rzp_key_id = trim($_POST['razorpay_key_id'] ?? '');
            $rzp_key_secret = trim($_POST['razorpay_key_secret'] ?? '');
            if ($rzp_key_id === '') $rzp_key_id = null;
            if ($rzp_key_secret === '') $rzp_key_secret = null;
        }
        $gst_option = trim($_POST['gst_option'] ?? 'excluding');
        $status = trim($_POST['status'] ?? 'draft');
        if (!in_array($status, ['draft', 'published'])) {
            $status = 'draft';
        }

        // File upload
        if (isset($_FILES['banner_file']) && $_FILES['banner_file']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = __DIR__ . '/../uploads';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            $tmp_name = $_FILES['banner_file']['tmp_name'];
            $original_name = $_FILES['banner_file']['name'];
            $ext = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
            
            $allowed_exts = ['jpg', 'jpeg', 'png', 'gif'];
            if (in_array($ext, $allowed_exts)) {
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                $mime = finfo_file($finfo, $tmp_name);
                finfo_close($finfo);
                
                $allowed_mimes = ['image/jpeg', 'image/png', 'image/gif'];
                if (in_array($mime, $allowed_mimes)) {
                    $file_name = bin2hex(random_bytes(16)) . '.' . $ext;
                    if (move_uploaded_file($tmp_name, $upload_dir . '/' . $file_name)) {
                        $banner_url = 'uploads/' . $file_name;
                    }
                }
            }
        }

        $location = '';
        $google_map_embed = '';
        $virtual_platform = '';
        $virtual_link = '';

        if ($event_type === 'physical' || $event_type === 'hybrid') {
            $location = trim($_POST['location'] ?? '');
            $google_map_embed = trim($_POST['google_map_embed'] ?? '');
        }
        if ($event_type === 'virtual' || $event_type === 'hybrid') {
            $virtual_platform = $_POST['virtual_platform'] ?? '';
            if (isset($_POST['auto_zoom']) && $virtual_platform === 'zoom') {
                $virtual_link = 'https://zoom.us/j/' . rand(100000000, 999999999);
            } else {
                $virtual_link = trim($_POST['virtual_link'] ?? '');
            }
            if ($event_type === 'virtual') {
                $location = 'Online Webcast';
            }
        }

        if (empty($title) || empty($start_date) || empty($end_date)) {
            $response['message'] = "Please fill in all required fields.";
        } else {
            try {
                $pdo->beginTransaction();

                $insert = $pdo->prepare("
                    INSERT INTO events (title, description, start_date, end_date, location, capacity, banner_url, event_type, google_map_embed, virtual_platform, virtual_link, payment_type, price, gst_option, created_by, status, razorpay_key_id, razorpay_key_secret) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $insert->execute([
                    $title, $description, $start_date, $end_date, 
                    $location, $capacity, $banner_url, $event_type, 
                    $google_map_embed, $virtual_platform, $virtual_link, 
                    $payment_type, $price, $gst_option, $currentUser['id'],
                    $status, $rzp_key_id, $rzp_key_secret
                ]);
                $newEventId = $pdo->lastInsertId();

                // Insert Agendas
                $agenda_items = json_decode($agenda_json, true) ?: [];
                $ins_agenda = $pdo->prepare("
                    INSERT INTO event_agendas (event_id, speaker_profile_id, agenda_date, start_time, end_time, title, speaker, description) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                ");
                foreach ($agenda_items as $item) {
                    $sp_id = !empty($item['speaker_profile_id']) ? (int)$item['speaker_profile_id'] : null;
                    $sp_name = !empty($item['speaker']) ? $item['speaker'] : null;
                    $ins_agenda->execute([
                        $newEventId, $sp_id, $item['agenda_date'], $item['start_time'], $item['end_time'], 
                        $item['topic'] ?? $item['title'], $sp_name, $item['description'] ?? ''
                    ]);
                }

                $pdo->commit();
                $response['success'] = true;
                $response['message'] = "Event created successfully.";
            } catch (PDOException $e) {
                if ($pdo->inTransaction()) $pdo->rollBack();
                $response['message'] = "Database error: " . $e->getMessage();
            }
        }
    } elseif (isset($_POST['submit_edit'])) {
        if (!$isAdmin) {
            $response['message'] = "Unauthorized action.";
            echo json_encode($response);
            exit();
        }

        $editId = (int)($_POST['event_id'] ?? 0);
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $start_date = trim($_POST['start_date'] ?? '');
        $end_date = trim($_POST['end_date'] ?? '');
        $event_type = $_POST['event_type'] ?? 'physical';
        $capacity = (int)($_POST['capacity'] ?? 0);
        $payment_type = trim($_POST['payment_type'] ?? 'free');
        $price = 0.00;
        $rzp_key_id = null;
        $rzp_key_secret = null;
        if ($payment_type === 'paid') {
            $price = (float)($_POST['price'] ?? 0.00);
            $rzp_key_id = trim($_POST['razorpay_key_id'] ?? '');
            $rzp_key_secret = trim($_POST['razorpay_key_secret'] ?? '');
            if ($rzp_key_id === '') $rzp_key_id = null;
            if ($rzp_key_secret === '') $rzp_key_secret = null;
        }
        $gst_option = trim($_POST['gst_option'] ?? 'excluding');
        $banner_url = trim($_POST['banner_url'] ?? '');
        $status = trim($_POST['status'] ?? 'draft');
        if (!in_array($status, ['draft', 'published'])) {
            $status = 'draft';
        }

        // Handle updated banner upload
        if (isset($_FILES['banner_file']) && $_FILES['banner_file']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = __DIR__ . '/../uploads';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
            $tmp_name = $_FILES['banner_file']['tmp_name'];
            $ext = strtolower(pathinfo($_FILES['banner_file']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif'])) {
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                $mime = finfo_file($finfo, $tmp_name);
                finfo_close($finfo);
                if (in_array($mime, ['image/jpeg', 'image/png', 'image/gif'])) {
                    $file_name = bin2hex(random_bytes(16)) . '.' . $ext;
                    if (move_uploaded_file($tmp_name, $upload_dir . '/' . $file_name)) {
                        $banner_url = 'uploads/' . $file_name;
                    }
                }
            }
        }

        $location = '';
        $google_map_embed = '';
        $virtual_platform = '';
        $virtual_link = '';
        if ($event_type === 'physical' || $event_type === 'hybrid') {
            $location = trim($_POST['location'] ?? '');
            $google_map_embed = trim($_POST['google_map_embed'] ?? '');
        }
        if ($event_type === 'virtual' || $event_type === 'hybrid') {
            $virtual_platform = $_POST['virtual_platform'] ?? '';
            $virtual_link = trim($_POST['virtual_link'] ?? '');
            if ($event_type === 'virtual') $location = 'Online Webcast';
        }

        if (empty($title) || empty($start_date) || empty($end_date) || $editId <= 0) {
            $response['message'] = "Please fill in all required fields.";
        } else {
            try {
                $upd = $pdo->prepare("
                    UPDATE events SET
                        title = ?, description = ?, start_date = ?, end_date = ?, location = ?,
                        capacity = ?, banner_url = ?, event_type = ?, google_map_embed = ?,
                        virtual_platform = ?, virtual_link = ?, payment_type = ?, price = ?,
                        gst_option = ?, status = ?, razorpay_key_id = ?, razorpay_key_secret = ?, updated_at = CURRENT_TIMESTAMP
                    WHERE id = ?
                ");
                $upd->execute([
                    $title, $description, $start_date, $end_date, $location,
                    $capacity, $banner_url, $event_type, $google_map_embed,
                    $virtual_platform, $virtual_link, $payment_type, $price,
                    $gst_option, $status, $rzp_key_id, $rzp_key_secret, $editId
                ]);
                $response['success'] = true;
                $response['message'] = "Event updated successfully.";
            } catch (PDOException $e) {
                error_log("Event edit error: " . $e->getMessage());
                $response['message'] = "Failed to update event. Please try again.";
            }
        }
    } elseif ($action === 'delete') {
        if (!$isAdmin) {
            $response['message'] = "Unauthorized.";
            echo json_encode($response);
            exit();
        }
        $deleteId = (int)($_POST['id'] ?? 0);
        try {
            $pdo->prepare("DELETE FROM events WHERE id = ?")->execute([$deleteId]);
            $response['success'] = true;
            $response['message'] = "Event deleted successfully.";
        } catch (PDOException $e) {
            error_log("Event delete error: " . $e->getMessage());
            $response['message'] = "Failed to delete event. Please try again.";
        }
    }
} else {
    // GET requests
    try {
        $tab = $_GET['tab'] ?? 'all';
        $search = trim($_GET['search'] ?? '');
        $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
        $limit = 9;
        $offset = ($page - 1) * $limit;

        $count_q = "";
        $data_q = "";
        $params = [];

        $allowedIds = getAccessibleEventIdsForUser($currentUser['id'], $currentUser['role'], $pdo);

        if ($tab === 'all') {
            $count_q = "SELECT COUNT(*) FROM events e WHERE 1=1";
            $data_q = "
                SELECT e.*, u.username as creator_name, COUNT(r.id) as attendee_count 
                FROM events e 
                LEFT JOIN users u ON e.created_by = u.id 
                LEFT JOIN registrations r ON e.id = r.event_id 
                WHERE 1=1
            ";
            
            if ($allowedIds !== null) {
                if (!empty($allowedIds)) {
                    $placeholders = implode(',', array_fill(0, count($allowedIds), '?'));
                    $count_q .= " AND e.id IN ($placeholders)";
                    $data_q .= " AND e.id IN ($placeholders)";
                    foreach ($allowedIds as $idVal) {
                        $params[] = $idVal;
                    }
                } else {
                    $count_q .= " AND 1=0";
                    $data_q .= " AND 1=0";
                }
            }
        } elseif ($tab === 'registered') {
            $count_q = "SELECT COUNT(*) FROM registrations r JOIN events e ON r.event_id = e.id WHERE r.user_id = ?";
            $data_q = "
                SELECT e.*, u.username as creator_name, COUNT(reg.id) as attendee_count 
                FROM events e 
                JOIN registrations r ON e.id = r.event_id 
                LEFT JOIN users u ON e.created_by = u.id
                LEFT JOIN registrations reg ON e.id = reg.event_id
                WHERE r.user_id = ?
            ";
            $params[] = $currentUser['id'];

            if ($allowedIds !== null) {
                if (!empty($allowedIds)) {
                    $placeholders = implode(',', array_fill(0, count($allowedIds), '?'));
                    $count_q .= " AND e.id IN ($placeholders)";
                    $data_q .= " AND e.id IN ($placeholders)";
                    foreach ($allowedIds as $idVal) {
                        $params[] = $idVal;
                    }
                } else {
                    $count_q .= " AND 1=0";
                    $data_q .= " AND 1=0";
                }
            }
        } elseif ($tab === 'hosted') {
            $count_q = "SELECT COUNT(*) FROM events e WHERE e.created_by = ?";
            $data_q = "
                SELECT e.*, u.username as creator_name, COUNT(r.id) as attendee_count 
                FROM events e 
                LEFT JOIN users u ON e.created_by = u.id 
                LEFT JOIN registrations r ON e.id = r.event_id 
                WHERE e.created_by = ?
            ";
            $params[] = $currentUser['id'];

            if ($allowedIds !== null) {
                if (!empty($allowedIds)) {
                    $placeholders = implode(',', array_fill(0, count($allowedIds), '?'));
                    $count_q .= " AND e.id IN ($placeholders)";
                    $data_q .= " AND e.id IN ($placeholders)";
                    foreach ($allowedIds as $idVal) {
                        $params[] = $idVal;
                    }
                } else {
                    $count_q .= " AND 1=0";
                    $data_q .= " AND 1=0";
                }
            }
        } elseif ($tab === 'speaking') {
            $count_q = "
                SELECT COUNT(DISTINCT e.id) FROM events e
                JOIN event_agendas ea ON e.id = ea.event_id
                JOIN speaker_profiles sp ON ea.speaker_profile_id = sp.id
                WHERE sp.user_id = ?
            ";
            $data_q = "
                SELECT e.*, u.username as creator_name, COUNT(r.id) as attendee_count 
                FROM events e 
                JOIN event_agendas ea ON e.id = ea.event_id 
                JOIN speaker_profiles sp ON ea.speaker_profile_id = sp.id 
                LEFT JOIN users u ON e.created_by = u.id
                LEFT JOIN registrations r ON e.id = r.event_id
                WHERE sp.user_id = ?
            ";
            $params[] = $currentUser['id'];

            if ($allowedIds !== null) {
                if (!empty($allowedIds)) {
                    $placeholders = implode(',', array_fill(0, count($allowedIds), '?'));
                    $count_q .= " AND e.id IN ($placeholders)";
                    $data_q .= " AND e.id IN ($placeholders)";
                    foreach ($allowedIds as $idVal) {
                        $params[] = $idVal;
                    }
                } else {
                    $count_q .= " AND 1=0";
                    $data_q .= " AND 1=0";
                }
            }
        } elseif ($tab === 'sponsoring') {
            $count_q = "
                SELECT COUNT(DISTINCT e.id) FROM events e
                JOIN event_sponsors es ON e.id = es.event_id
                JOIN sponsor_profiles sp ON es.sponsor_profile_id = sp.id
                WHERE sp.user_id = ?
            ";
            $data_q = "
                SELECT e.*, u.username as creator_name, COUNT(r.id) as attendee_count 
                FROM events e 
                JOIN event_sponsors es ON e.id = es.event_id 
                JOIN sponsor_profiles sp ON es.sponsor_profile_id = sp.id 
                LEFT JOIN users u ON e.created_by = u.id
                LEFT JOIN registrations r ON e.id = r.event_id
                WHERE sp.user_id = ?
            ";
            $params[] = $currentUser['id'];

            if ($allowedIds !== null) {
                if (!empty($allowedIds)) {
                    $placeholders = implode(',', array_fill(0, count($allowedIds), '?'));
                    $count_q .= " AND e.id IN ($placeholders)";
                    $data_q .= " AND e.id IN ($placeholders)";
                    foreach ($allowedIds as $idVal) {
                        $params[] = $idVal;
                    }
                } else {
                    $count_q .= " AND 1=0";
                    $data_q .= " AND 1=0";
                }
            }
        }

        if (!$isAdmin) {
            $count_q .= " AND e.status = 'published'";
            $data_q .= " AND e.status = 'published'";
        }

        if (!empty($search)) {
            $count_q .= " AND (e.title ILIKE ? OR e.location ILIKE ?)";
            $data_q .= " AND (e.title ILIKE ? OR e.location ILIKE ?)";
            $params[] = "%$search%";
            $params[] = "%$search%";
        }

        $data_q .= " GROUP BY e.id, u.username";

        $stmt_c = $pdo->prepare($count_q);
        $stmt_c->execute($params);
        $total = (int)$stmt_c->fetchColumn();

        $data_q .= " ORDER BY e.start_date ASC LIMIT ? OFFSET ?";
        $stmt_d = $pdo->prepare($data_q);
        foreach ($params as $idx => $val) {
            $stmt_d->bindValue($idx + 1, $val);
        }
        $stmt_d->bindValue(count($params) + 1, $limit, PDO::PARAM_INT);
        $stmt_d->bindValue(count($params) + 2, $offset, PDO::PARAM_INT);
        $stmt_d->execute();

        $response['events'] = $stmt_d->fetchAll(PDO::FETCH_ASSOC) ?: [];
        $response['total_pages'] = max(1, ceil($total / $limit));
        $response['page'] = $page;
        $response['success'] = true;
    } catch (PDOException $e) {
        $response['message'] = "Database error: " . $e->getMessage();
    }
}

echo json_encode($response);
