<?php
session_start(); // Ensure session is started
require('../config.php');
header('Content-Type: application/json');
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
// Check database connection
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_temp'])) {

    // Fetch templates securely using a prepared statement
    $sql = "SELECT id, client_id, template_name, template_category, template_language, template_type, 
                   template_media_type, template_media_content, template_body, template_footer, created_at, updated_at 
            FROM client_templates WHERE client_id = ?";
    $stmt = mysqli_prepare($db, $sql);
    mysqli_stmt_bind_param($stmt, "i", $clientId);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);


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

    // Check if templates exist and return response
    $templates = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $templates[] = $row;
    }
    mysqli_stmt_close($stmt);

    if (!empty($templates)) {
        echo json_encode(['status' => 'success', 'data' => $templates]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'No templates found for this client']);
    }
}

if (isset($_GET['client_contacts'])) {
    // Build the base query with potential filter joins
    $filterJoins = '';
    $filterWhereConditions = [];
    
    // Process filters if they exist
    if (isset($_GET['filters']) && !empty($_GET['filters'])) {
        $filters = json_decode($_GET['filters'], true);

        if ($filters && is_array($filters)) {
            // Since attribute names are unique per contact,
            // join contact_attributes once per attribute name only
            foreach ($filters as $index => $filter) {
                if (empty($filter['attribute_name']) || empty($filter['operation'])) {
                    continue;
                }

                $attributeName = mysqli_real_escape_string($db, $filter['attribute_name']);
                $operation = $filter['operation'];
                $attributeValue = isset($filter['attribute_value']) ? mysqli_real_escape_string($db, $filter['attribute_value']) : '';

                // Alias for the join - one per filter attribute
                $filterAlias = "ca_filter_$index";

                // Add join for this attribute name once
                $filterJoins .= " LEFT JOIN contact_attributes $filterAlias ON c.id = $filterAlias.contact_id AND $filterAlias.attri_name = '$attributeName' ";

                // Build where condition based on operation
                switch ($operation) {
                    case 'contains':
                        if ($attributeValue !== '') {
                            $filterWhereConditions[] = "$filterAlias.attri_value LIKE '%$attributeValue%'";
                        }
                        break;
                    case 'does not contain':
                        if ($attributeValue !== '') {
                            $filterWhereConditions[] = "($filterAlias.attri_value NOT LIKE '%$attributeValue%' OR $filterAlias.attri_value IS NULL)";
                        }
                        break;
                    case 'exists':
                        $filterWhereConditions[] = "$filterAlias.attri_value IS NOT NULL AND $filterAlias.attri_value != ''";
                        break;
                    case 'does not exist':
                        $filterWhereConditions[] = "($filterAlias.attri_value IS NULL OR $filterAlias.attri_value = '')";
                        break;
                    case '=':
                        if ($attributeValue !== '') {
                            $filterWhereConditions[] = "$filterAlias.attri_value = '$attributeValue'";
                        }
                        break;
                    case '!=':
                        if ($attributeValue !== '') {
                            $filterWhereConditions[] = "($filterAlias.attri_value != '$attributeValue' OR $filterAlias.attri_value IS NULL)";
                        }
                        break;
                    case '>':
                        if ($attributeValue !== '') {
                            $filterWhereConditions[] = "CAST($filterAlias.attri_value AS DECIMAL(10,2)) > CAST('$attributeValue' AS DECIMAL(10,2))";
                        }
                        break;
                    case '<':
                        if ($attributeValue !== '') {
                            $filterWhereConditions[] = "CAST($filterAlias.attri_value AS DECIMAL(10,2)) < CAST('$attributeValue' AS DECIMAL(10,2))";
                        }
                        break;
                    case '>=':
                        if ($attributeValue !== '') {
                            $filterWhereConditions[] = "CAST($filterAlias.attri_value AS DECIMAL(10,2)) >= CAST('$attributeValue' AS DECIMAL(10,2))";
                        }
                        break;
                    case '<=':
                        if ($attributeValue !== '') {
                            $filterWhereConditions[] = "CAST($filterAlias.attri_value AS DECIMAL(10,2)) <= CAST('$attributeValue' AS DECIMAL(10,2))";
                        }
                        break;
                }
            }
        }
    }

    $baseWhereCondition = "c.client_id = '$clientId' AND ca.attri_name = 'allowbroadcast'";

    if (!empty($filterWhereConditions)) {
        $baseWhereCondition .= " AND (" . implode(' AND ', $filterWhereConditions) . ")";
    }

    $table = <<<EOT
    (
        SELECT 
            c.id,
            c.client_id,
            c.name,
            c.country_code,
            c.phone,
            ca.attri_name,
            ca.attri_value
        FROM contacts c
        LEFT JOIN contact_attributes ca ON c.id = ca.contact_id
        $filterJoins
        WHERE $baseWhereCondition
    ) AS join_table
    EOT;

    $whereResult = null;
    $orderBy = null;
    $sql_details = $search_db;

    if (isset($_GET['all_leads_where_clause']) && !empty($_GET['all_leads_where_clause'])) {
        $whereAll = $_GET['all_leads_where_clause'];
    } else {
        $whereAll = null;
    }

    if (isset($_GET['extrawhere'])) {
        $whereResult = $_GET['extrawhere'];
    }

    $primaryKey = 'id';

    $columns = array(
        array(
            'db' => 'id',
            'dt' => 'id',
            'formatter' => function ($cell) {
                return "<span><input type='checkbox' style='transform: scale(1.4);' data-contact-id='" . $cell . "' name='contactdata' class='contactdata' value='" . $cell . "'></span>";
            }
        ),
        array(
            'db' => 'name',
            'dt' => 'name'
        ),
        array(
            'db' => 'phone',
            'dt' => 'phone',
            'formatter' => function ($cell, $row) {
                return '+' . $row['country_code'] . ' ' . $cell;
            }
        ),
        array(
            'db' => 'country_code',
            'dt' => 'country_code'
        ),
        array(
            'db' => 'attri_value',
            'dt' => 'Allow Broadcast',
            'formatter' => function ($cell, $row) {
                if (strtolower($cell) == "true") {
                    return "<p class='fw-medium rounded-pill d-inline-block' style='background: darkseagreen; color: white; margin-bottom:0px; padding: 8px 1.6rem; font-size:small;'>
                            $cell
                        </p>";
                } else {
                    return "<p class='fw-medium rounded-pill d-inline-block' style='background: #ff000057; color: red; margin-bottom:0px; padding: 8px 1.6rem; font-size:small;'>
                            $cell
                        </p>";
                }
            }
        )
    );


    require('../get_data_from_server/ssp.class.php');

    echo json_encode(
        SSP::complex($_GET, $sql_details, $table, $primaryKey, $columns, $whereResult, $whereAll, $orderBy)
    );

    // Get the DataTables result first
    // $result = SSP::complex($_GET, $sql_details, $table, $primaryKey, $columns, $whereResult, $whereAll, $orderBy);

    // Add debug information
    // $debugInfo = array(
    //     'table' => $table,
    //     'baseWhereCondition' => $baseWhereCondition,
    //     'filterJoins' => $filterJoins,
    //     'filterWhereConditions' => $filterWhereConditions,
    //     'final_query' => "SELECT * FROM $table WHERE $baseWhereCondition"
    // );

    // // Add debug info to the result
    // $result['debug'] = true;
    // $result['query_info'] = $debugInfo;

    // echo json_encode($result);
}

if (isset($_GET['contacts_count'])) {
    $sql = "SELECT COUNT(*) AS total_contacts FROM contacts WHERE client_id = $clientId";
    $result = mysqli_query($db, $sql);

    if (!$result) {
        echo json_encode(["status" => "error", "message" => mysqli_error($db)]);
        exit;
    }
    $row = mysqli_fetch_assoc($result); // fetch the actual data

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

if (isset($_GET['contacts_attributes'])) {
    // $sql = "SELECT attri_name AS attribute_name, attri_value AS attribute_value FROM contact_attributes WHERE client_id = $clientId";
    $sql = "
        SELECT attribute_name,
            JSON_ARRAYAGG(attri_value) AS attribute_value
        FROM (
            SELECT DISTINCT attri_name AS attribute_name, attri_value
            FROM contact_attributes
            WHERE client_id = $clientId
        ) AS unique_attrs
        GROUP BY attribute_name;
    ";
    $result = mysqli_query($db, $sql);

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

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

mysqli_close($db);
?>