<?php
session_start(); // Ensure session is started
require('../config.php');
header('Content-Type: application/json');
// error_reporting(E_ALL); // Display all errors
// ini_set('display_errors', 1); // Display errors in the browser

// Check if the database connection is valid
if (!$db) {
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
    exit;
}

// Debugging: Check if session contains client_id
if (!isset($_SESSION['client_id']) || empty($_SESSION['client_id']) || !is_numeric($_SESSION['client_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'User not authenticated or session expired']);
    exit;
}
$clientId = (int)$_SESSION['client_id'];

if (isset($_GET['fetch_broadcast'])) {
    // Extract filters from query parameters
    $search = $_GET['search'] ?? '';
    $sort_by = $_GET['sort_by'] == "latest" ? "DESC" : "ASC";
    $filterType = $_GET['filter_type'] ?? '';
    $startDate = $_GET['start_date'] ?? '';
    $endDate = $_GET['end_date'] ?? '';

    $sql = "
        SELECT
            b.id AS broadcast_id,
            b.broadcast_name, 
            b.scheduled_at, 
            b.created_at, 
            COUNT(bc.contact_id) AS Total_recipients 
        FROM 
            broadcasts b 
        LEFT JOIN 
            broadcast_contacts bc ON b.id = bc.broadcast_id 
        WHERE 
            b.client_id = '$clientId'
    ";

    // Apply filter based on selected time range
    switch ($filterType) {
        case 'yesterday':
            $sql .= " AND DATE(b.created_at) = CURDATE() - INTERVAL 1 DAY";
            break;
        case 'last_7_days':
            $sql .= " AND DATE(b.created_at) >= CURDATE() - INTERVAL 6 DAY ";
            break;
        case 'last_30_days':
            $sql .= " AND DATE(b.created_at) >= CURDATE() - INTERVAL 29 DAY ";
            break;
        case 'custom_range':
            $sql .= " AND DATE(b.created_at) BETWEEN '$startDate' AND '$endDate'";
            break;
        default:
            $sql .= " AND DATE(b.created_at) = CURDATE()";
    }

    if (!empty($search)) {
        $sql .= " AND b.broadcast_name LIKE '%$search%'";
    }
    $sql .= "
        GROUP BY 
            b.id
        ORDER BY 
            b.created_at $sort_by
    ";

    $result = mysqli_query($db, $sql);
    $rows = [];

    while ($row = mysqli_fetch_assoc($result)) {
        $rows[] = $row;
    }

    if (!$result) {
        echo json_encode(["status" => "error", "message" => mysqli_error($db)]);
        exit;
    }

    echo json_encode(["status" => "success", "data" => $rows]);
}

if (isset($_GET['add_broadcast'])) {
    // Fetch and sanitize form data
    $broadcast_name    = mysqli_real_escape_string($db, $_POST['broadcast_name'] ?? '');
    $selected_template = (int)($_POST['selected_template']);
    $send_type         = mysqli_real_escape_string($db, $_POST['send_type'] ?? '');
    $schedule_at       = mysqli_real_escape_string($db, $_POST['schedule_at'] ?? '');
    $selected_contacts = $_POST['selected_contacts'] ?? '';

    // Validate required fields
    if (empty($selected_template)) {
        echo json_encode(['status' => 'error', 'message' => 'Missing fields: selected_template']);
        exit;
    }
    if (empty($broadcast_name)) {
        echo json_encode(['status' => 'error', 'message' => 'Missing fields: broadcast_name']);
        exit;
    }
    if (empty($send_type)) {
        echo json_encode(['status' => 'error', 'message' => 'Missing field: send_type']);
        exit;
    }
    if (empty($selected_contacts)) {
        echo json_encode(['status' => 'error', 'message' => 'Missing field: selected_contacts']);
        exit;
    }

    if (count($selected_contacts) === 0) {
        echo json_encode(['status' => 'error', 'message' => 'No valid contacts selected.']);
        exit;
    }

    $schedule_at = ($schedule_at === 'now') ? "NOW()" : "'" . mysqli_real_escape_string($db, $schedule_at) . "'";

    // Begin transaction
    mysqli_begin_transaction($db);
    try {
        // Insert broadcast
        $broadcast_sql = "
            INSERT INTO broadcasts (client_id, broadcast_name, template_id, send_type, scheduled_at)
            VALUES ($clientId, '$broadcast_name', $selected_template, '$send_type', $schedule_at)
        ";

        if (!mysqli_query($db, $broadcast_sql)) {
            throw new Exception("Broadcast Insert Failed: " . mysqli_error($db));
        }

        $broadcast_id = mysqli_insert_id($db);

        // Insert broadcast_contacts
        foreach ($selected_contacts as $contact_id) {
            $contact_id = (int)trim($contact_id);
            $contact_sql = "
                INSERT INTO broadcast_contacts (broadcast_id, contact_id)
                VALUES ($broadcast_id, $contact_id)
            ";
            if (!mysqli_query($db, $contact_sql)) {
                throw new Exception("Contact Insert Failed: " . mysqli_error($db));
            }
        }

        // Commit transaction
        mysqli_commit($db);
        echo json_encode(['status' => 'success', 'message' => 'Broadcast created successfully.']);
    } catch (Exception $e) {
        mysqli_rollback($db);
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
}

if (isset($_GET['export_broadcast'])) {
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');
    header('Connection: keep-alive');

    // For SSE, we need to get broadcast_ids from GET parameter
    if (!isset($_GET['broadcast_ids']) || empty($_GET['broadcast_ids'])) {
        echo "data: " . json_encode(["error" => "Missing broadcast_ids"]) . "\n\n";
        exit;
    }

    $broadcast_ids = $_GET['broadcast_ids'];

    // Your existing SQL query
    $sql = "SELECT 
                DATE_FORMAT(b.scheduled_at, '%m/%d/%Y %r') AS scheduled_at,
                CONCAT('+', c.country_code, c.phone) AS phone_number,
                b.broadcast_name,
                ct.template_name
            FROM broadcasts b
            LEFT JOIN broadcast_contacts bc ON b.id = bc.broadcast_id
            LEFT JOIN contacts c ON bc.contact_id = c.id
            LEFT JOIN client_templates ct ON b.template_id = ct.id
            WHERE b.client_id = $clientId AND b.id IN ($broadcast_ids)";

    $result = mysqli_query($db, $sql);

    if (!$result) {
        echo "data: " . json_encode(["error" => "Database error"]) . "\n\n";
        exit;
    }

    if (mysqli_num_rows($result) === 0) {
        echo "data: " . json_encode(["error" => "No data found"]) . "\n\n";
        exit;
    }

    // Fetch all data
    $data = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = $row;
    }

    // Build CSV content with progress updates
    $csv_content = '';
    $csv_header = ['Schedule_at', 'phone_number', 'broadcast_name', 'template_name', 'status'];
    $csv_content .= implode(',', array_map(function ($field) {
        return '"' . str_replace('"', '""', $field) . '"';
    }, $csv_header)) . "\n";

    $total_rows = count($data);
    $target_total_time_ms = 3000;
    $delay_per_row_us = intval(($target_total_time_ms * 1000) / max(1, $total_rows));
    $processed = 0;

    // Send initial progress
    echo "data: " . json_encode(["progress" => 0]) . "\n\n";
    flush();

    foreach ($data as $row) {
        $row['status'] = 'pending';
        $csv_row = array_map(function ($field) {
            return '"' . str_replace('"', '""', $field) . '"';
        }, array_values($row));

        $csv_content .= implode(',', $csv_row) . "\n";
        $processed++;

        $percentage = intval(($processed / $total_rows) * 100);

        // Send progress update
        echo "data: " . json_encode(["progress" => $percentage]) . "\n\n";
        flush();

        usleep($delay_per_row_us); // Small delay to see progress
    }

    // Send final CSV data
    echo "data: " . json_encode([
        "progress" => 100,
        "csv_data" => $csv_content,
        "complete" => true
    ]) . "\n\n";
    flush();
    exit;
}

mysqli_close($db);
