<?php
    require_once('../config.php');

    if (isset($_GET['template_id']) && isset($_GET['find_template'])) {
        header('Content-Type: application/json');

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

        $template_id = (int)$_GET['template_id'];
        $sql = "SELECT * FROM client_templates WHERE id = '$template_id'";

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

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

        $template = mysqli_fetch_assoc($data); // Get single row

        if (!$template) {
            echo json_encode(['status' => 'error', 'message' => 'Template not found']);
            exit;
        }

        // Only fetch standard type template data
        if (isset($template['template_type']) && $template['template_type'] === "standard") {
            $button_sql_query = "SELECT * FROM template_buttons WHERE template_id = '$template_id'";
            $button_data = mysqli_query($db, $button_sql_query);

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

            // Add buttons data to template array
            $buttons = [];
            while ($row = mysqli_fetch_assoc($button_data)) {
                $buttons[] = $row;
            }

            $template['buttons'] = $buttons; // Append buttons under 'buttons' key
        }

        // Only fetch carousel type template data
        if (isset($template['template_type']) && $template['template_type'] === "carousel") {
            $carousel_sql_query = "SELECT * FROM template_carousels WHERE template_id = '$template_id'";
            $carousel_data = mysqli_query($db, $carousel_sql_query);

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

            $carousels = [];

            while ($carousel = mysqli_fetch_assoc($carousel_data)) {
                $carousel_id = $carousel['id'];

                // Fetch buttons for each carousel
                $button_sql_query = "SELECT * FROM template_carousel_buttons WHERE template_id = '$template_id' AND carousel_id = '$carousel_id'";
                $button_data = mysqli_query($db, $button_sql_query);

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

                $buttons = [];
                while ($btn = mysqli_fetch_assoc($button_data)) {
                    $buttons[] = $btn;
                }

                // Add buttons to the current carousel
                $carousel['buttons'] = $buttons;

                // Add this carousel to the carousels array
                $carousels[] = $carousel;
            }

            // Attach all carousels with their buttons to the template
            $template['carousels'] = $carousels;
        }

        echo json_encode([
            'status' => 'success',
            'template_data' => $template, // all combined in a single associative object
        ]);
        exit;
    }


    if(isset($_GET['template_data'])){
        $sql_details = $search_db;
        
        if (!isset($_SESSION['client_id'])) {
            echo json_encode(['status' => 'error', 'message' => 'Client ID not found in session']);
            exit;
        }
        $clientId = mysqli_real_escape_string($db, $_SESSION['client_id']);
        // Define CASE statements to convert numeric codes into strings (used for sorting and filtering)
        
        if(isset($_GET['sort_by_createdAt']) && $_GET['sort_by_createdAt'] ){
            $columnName = "created_at";
        }else{
            $columnName = "template_name";
        }

        $categoryCase = "CASE template_category 
            WHEN '1' THEN 'Authentication'
            WHEN '2' THEN 'Marketing'
            WHEN '3' THEN 'Utility'
            ELSE 'Unknown' END AS template_category_label";
        
        $languageCase = "CASE template_language
            WHEN '1' THEN 'English'
            WHEN '2' THEN 'Hindi'
            WHEN '3' THEN 'Spanish'
            WHEN '4' THEN 'French'
            WHEN '5' THEN 'German'
            WHEN '6' THEN 'Chinese'
            WHEN '7' THEN 'Japanese'
            WHEN '8' THEN 'Korean'
            WHEN '9' THEN 'Russian'
            WHEN '10' THEN 'Arabic'
            WHEN '11' THEN 'Portuguese'
            WHEN '12' THEN 'Bengali'
            WHEN '13' THEN 'Italian'
            WHEN '14' THEN 'Urdu'
            WHEN '15' THEN 'Turkish'
            ELSE 'Unknown' END AS template_language_label";
        
        // Use CASE in subquery to allow proper sorting
        $table = <<<EOT
        (
            SELECT 
                id,
                template_name,
                template_category,
                template_type,
                template_language,
                updated_at,
                created_at,
                $categoryCase,
                $languageCase
            FROM client_templates where client_id = '$clientId'
            ORDER BY $columnName DESC
        ) AS join_table
        EOT;
        
        $whereResult = null;
        
        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'];
        }
        
        // Handle search for category and language
        if (isset($_GET['search']['value']) && !empty($_GET['search']['value'])) {
            $searchValue = $_GET['search']['value'];
        
            if (isset($sql_details['connection'])) {
                $mysqli = $sql_details['connection'];
                $searchValueEscaped = $mysqli->real_escape_string($searchValue);
            } else {
                $searchValueEscaped = str_replace(["'", "\\"], ["\'", "\\\\"], $searchValue);
            }
        
            $customWhere = "(
                template_category_label LIKE '%$searchValueEscaped%' OR
                template_language_label LIKE '%$searchValueEscaped%' OR
                template_name LIKE '%$searchValueEscaped%' OR
                DATE_FORMAT(updated_at, '%d/%m/%Y') LIKE '%$searchValueEscaped%'
            )";
            
            if ($whereAll) {
                $whereAll = "($whereAll) AND $customWhere";
            } else {
                $whereAll = $customWhere;
            }
        
            $_GET['search']['value'] = '';
        }
        
        $primaryKey = 'id';
        
        $columns = array(
            array(
                'db' => 'id',
                'dt' => 'id',
                'formatter' => function ($cell, $row) {
                    return "<span><input type='checkbox' data-lead-id='" . $cell . "' name='leadsdata' class='leadsdata' value='" . $cell . "'></span>";
                }
            ),
            array(
                'db' => 'template_name',
                'dt' => 'template_name'
            ),
            array(
                'db' => 'template_category_label',
                'dt' => 'template_category'
            ),
            array(
                'db'=>null,
                'dt'=> 'status',
                'formatter'=> function (){
                    return "
                        <div class='px-2 py-2 rounded-pill fw-medium text-center' style='background: #0080006e;'>
                        <p class='mb-0' style='color: white;'>Approved</p>
                        </div>
                    ";
                }
            ),
            array(
                'db' => 'template_language_label',
                'dt' => 'template_language'
            ),
            array(
                'db' => 'template_type',
                'dt' => 'template_type' 
            ),
            array(
                'db' => 'created_at',
                'dt' => 'created_at',
                'formatter' => function($cell) {
                    if (!$cell) return '';
                    
                    // Check if we have a valid timestamp
                    if (is_numeric($cell)) {
                        return date('d/m/Y', $cell);
                    }
                    
                    // Try to parse the date string
                    $timestamp = strtotime($cell);
                    if ($timestamp !== false) {
                        return date('d/m/Y', $timestamp);
                    }
                    
                    // If all else fails, return original value
                    return $cell;
                }
            ),
            array(
                'db' => 'updated_at',
                'dt' => 'updated_at',
                'formatter' => function($cell) {
                    if (!$cell) return '';
                    
                    // Check if we have a valid timestamp
                    if (is_numeric($cell)) {
                        return date('d/m/Y', $cell);
                    }
                    
                    // Try to parse the date string
                    $timestamp = strtotime($cell);
                    if ($timestamp !== false) {
                        return date('d/m/Y', $timestamp);
                    }
                    
                    // If all else fails, return original value
                    return $cell;
                }
            ),
            array(
                'db' => 'id',
                'dt' => 'actions',
                'formatter' => function($cell, $row) {
                    return "<div class='text-center'>
                            <button class='btn btn-outline-success editMessageTemplate' data-message-template-id='$cell'>
                                <svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' style='fill: #009688;' class='actionBtn' data-message-template-id='$cell'>
                                    <path d='m7 17.013 4.413-.015 9.632-9.54c.378-.378.586-.88.586-1.414s-.208-1.036-.586-1.414l-1.586-1.586c-.756-.756-2.075-.752-2.825-.003L7 12.583v4.43zM18.045 4.458l1.589 1.583-1.597 1.582-1.586-1.585 1.594-1.58zM9 13.417l6.03-5.973 1.586 1.586-6.029 5.971L9 15.006v-1.589z'></path>
                                    <path d='M5 21h14c1.103 0 2-.897 2-2v-8.668l-2 2V19H8.158c-.026 0-.053.01-.079.01-.033 0-.066-.009-.1-.01H5V5h6.847l2-2H5c-1.103 0-2 .897-2 2v14c0 1.103.897 2 2 2z'></path>
                                </svg>
                            </button>
                            <button class='btn btn-outline-danger deleteMessageTemplate' data-message-template-id='$cell' data-template-type=\"{$row['template_type']}\">
                                <svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' style='fill: #F44336;' class='deleteBtn'>
                                    <path d='M5 20a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8h2V6h-4V4a2 2 0 0 0-2-2H9a2 2 0 0 0-2 2v2H3v2h2zM9 4h6v2H9zM8 8h9v12H7V8z'></path>
                                    <path d='M9 10h2v8H9zm4 0h2v8h-2z'></path>
                                </svg>
                            </button>
                        </div>";
                }
            )
        );
        
        require('ssp.class.php');
        
        echo json_encode(
            SSP::complex($_GET, $sql_details, $table, $primaryKey, $columns, $whereResult, $whereAll, $orderBy)
        );

    }
?>
