<?php
    require('../config.php');
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    header('Content-Type: application/json');

    // ✅ Check DB connection
    if (!$db) {
        echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
        exit;
    }
    // ✅ Get clientId from session
    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']);
    $templateName         = mysqli_real_escape_string($db, $_POST['templateName'] ?? '');
    $templateCategory     = mysqli_real_escape_string($db, $_POST['templateCategory'] ?? '');
    $templateLanguage     = mysqli_real_escape_string($db, $_POST['templateLanguage'] ?? '');
    $templateType         = mysqli_real_escape_string($db, $_POST['templateType'] ?? '');
    $templateBody         = mysqli_real_escape_string($db, $_POST['templateBody'] ?? '');
    $templateFooter       = mysqli_real_escape_string($db, $_POST['previewMessageFooterInput'] ?? '');
    $templateMediaContent = [];

    if($templateType === "standard"){
        // ✅ Collect fields
        $templateMediaType    = mysqli_real_escape_string($db, $_POST['templateMediatype'] ?? '');
        $templateMediaContent = mysqli_real_escape_string($db, $_POST['broadcastTitleInput'] ?? '');
    
        $text_content = mysqli_real_escape_string($db, $_POST['text_content'] ?? '');
        if(!empty(trim($text_content))){
            $templateMediaContent = $text_content;
        }
    
        $structuredButtonsRaw = $_POST['structuredButtons'] ?? '[]';
        $copyButtonItemsRaw   = $_POST['copyButtonItems'] ?? '[]';
    
        // ✅ Validate required fields
        $required_fields = [$templateName, $templateCategory, $templateLanguage, $templateType, $templateMediaType, $templateBody];
        $field_names = ['templateName', 'templateCategory', 'templateLanguage', 'templateType', 'templateMediaType', 'templateBody'];
    
        foreach ($required_fields as $index => $field) {
            if (empty($field)) {
                echo json_encode(['status' => 'error', 'message' => 'Missing field: ' . $field_names[$index]]);
                exit;
            }
        }
    
        // ✅ Handle image upload
        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            if ($_FILES['image']['size'] > 2 * 1024 * 1024) {
                echo json_encode(['status' => 'error', 'message' => 'Image file is too large. Max size allowed is 2MB']);
                exit;
            }

            $uploadDir = '../images/template-images';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
    
            $fileTmp    = $_FILES['image']['tmp_name'];
            $fileName   = time() . '_' . basename($_FILES['image']['name']);
            $uploadPath = $uploadDir . '/' . $fileName;
    
            if (move_uploaded_file($fileTmp, $uploadPath)) {
                $templateMediaContent = 'https://app.watify.io/images/template-images/' . $fileName;
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Failed to save uploaded image']);
                exit;
            }
        }

        // Handle video upload
        if(isset($_FILES['video']) && $_FILES['video']['error'] === UPLOAD_ERR_OK){
            if ($_FILES['video']['size'] > 2 * 1024 * 1024) {
                echo json_encode(['status' => 'error', 'message' => 'Video file is too large. Max size allowed is 2MB']);
                exit;
            }
            $uploadDir = '../images/template-videos';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
    
            $fileTmp    = $_FILES['video']['tmp_name'];
            $fileName   = time() . '_' . basename($_FILES['video']['name']);
            $uploadPath = $uploadDir . '/' . $fileName;
    
            if (move_uploaded_file($fileTmp, $uploadPath)) {
                $templateMediaContent = 'https://app.watify.io/images/template-videos/' . $fileName;
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Failed to save uploaded video']);
                exit;
            }
        }

        // Handle document upload
        if(isset($_FILES['document']) && $_FILES['document']['error'] === UPLOAD_ERR_OK){
            if ($_FILES['document']['size'] > 2 * 1024 * 1024) {
                echo json_encode(['status' => 'error', 'message' => 'document file is too large. Max size allowed is 2MB']);
                exit;
            }
            $uploadDir = '../images/template-documents';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
    
            $fileTmp    = $_FILES['document']['tmp_name'];
            $fileName   = time() . '_' . basename($_FILES['document']['name']);
            $uploadPath = $uploadDir . '/' . $fileName;
    
            if (move_uploaded_file($fileTmp, $uploadPath)) {
                $templateMediaContent = 'https://app.watify.io/images/template-documents/' . $fileName;
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Failed to save uploaded document']);
                exit;
            }
        }

        // ✅ Handle copy buttons
        $copyButtonItems = json_decode($copyButtonItemsRaw, true);
        $copyTexts = [];
        $copyCodes = [];
    
        foreach ($copyButtonItems as $item) {
            $copyTexts[] = trim($item['offerText']);
            $copyCodes[] = trim($item['couponCode']);
        }
        $copyTextString = mysqli_real_escape_string($db, implode(',', $copyTexts));
        $copyCodeString = mysqli_real_escape_string($db, implode(',', $copyCodes));
    
        // ✅ Insert new template
        $sql = "INSERT INTO client_templates (
        client_id, template_name, template_category, template_language, 
        template_type, template_media_type, template_media_content, 
        template_body, template_footer, copy_text, copy_code
        ) VALUES (
            '$clientId', '$templateName', '$templateCategory', '$templateLanguage', 
            '$templateType', '$templateMediaType', '$templateMediaContent', 
            '$templateBody', '$templateFooter', '$copyTextString', '$copyCodeString'
        )";

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

        $templateId = mysqli_insert_id($db);

        
        // ✅ Handle structured buttons only
        $structuredButtons = json_decode($structuredButtonsRaw, true);
        if (is_array($structuredButtons) && count($structuredButtons)) {
            foreach ($structuredButtons as $button) {
                $fieldType = mysqli_real_escape_string($db, $button['field-type'] ?? '');
                $linkType  = isset($button['link-type']) ? "'" . mysqli_real_escape_string($db, $button['link-type']) . "'" : "NULL";
                $link      = isset($button['link']) ? "'" . mysqli_real_escape_string($db, $button['link']) . "'" : "NULL";
                $text      = isset($button['text']) ? "'" . mysqli_real_escape_string($db, $button['text']) . "'" : "NULL";
                $number    = isset($button['number']) ? "'" . mysqli_real_escape_string($db, $button['number']) . "'" : "NULL";
              
                $btnSql = "INSERT INTO template_buttons (
                    template_id, button_type, text, link_type, link, phone_number
                ) VALUES (
                    '$templateId', '$fieldType', $text, $linkType, $link, $number
                )";

                if (!mysqli_query($db, $btnSql)) {
                    echo json_encode(['status' => 'error', 'message' => 'Button insert failed: ' . mysqli_error($db)]);
                    exit;
                }
            }
        }
    
        // ✅ Done
        echo json_encode([
            'status' => 'success',
            'message' => 'Template saved successfully'
        ]);
    }
    else{
        $carouselData='';

        if(!isset($_POST['templateCarouselData'])){
            echo json_encode(['status'=>'error','message'=> 'Missing Field: Carousel Data']);
            exit;
        }else{
            $carouselData = json_decode($_POST['templateCarouselData'],true);
            
            if(!is_array($carouselData)){
                echo json_encode(['status'=> 'error', 'message'=> 'Invalid Carousel JSON']);
                exit;
            }
            // $fileDebugInfo = [];

            // foreach ($_FILES as $key => $file) {
            //     $fileDebugInfo[$key] = [
            //         'name'     => $file['name'],
            //         'type'     => $file['type'],
            //         'tmp_name' => $file['tmp_name'],
            //         'error'    => $file['error'],
            //         'size'     => $file['size'],
            //     ];
            // }
            
            // echo json_encode(['status' => 'success', 'files' => $fileDebugInfo]);
            // exit;
            
            //check image size is not more than 2mb and image extension must be .webp
            for($i=0; $i<count($carouselData);$i++){
                if(isset($_FILES['card-image-'.($i+1)])){
                    $file = $_FILES['card-image-' . ($i + 1)];
                    $fileName = $file['name'];
                    $fileSize = $file['size'];
                    $fileTmp = $file['tmp_name'];
                    $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    
                    if($fileSize > 2 * 1024 * 1024){
                        echo json_encode(['status' => 'error', 'message' => 'File is too large.']);
                        exit;
                    }else if($fileExtension != 'webp'){
                        echo json_encode(['status' => 'error', 'message' => 'File extension must be webp.']);
                        exit;
                    }else{
                        // Handle image
                        $uploadDir = '../client_media/images';
                        $uniqueFileName = uniqid() . '-' . basename($fileName);
                        $uploadPath = $uploadDir . '/' . $uniqueFileName;
                
                        if (move_uploaded_file($fileTmp, $uploadPath)) {
                            $templateMediaContent[] = 'https://app.watify.io/client_media/images/' . $uniqueFileName;
                        } else {
                            echo json_encode(['status' => 'error', 'message' => 'Failed to save uploaded image']);
                            exit;
                        }
                    }
                }else if(isset($_FILES['card-video-'.($i+1)])){
                    $file = $_FILES['card-video-' . ($i + 1)];
                    $fileName = $file['name'];
                    $fileSize = $file['size'];
                    $fileTmp = $file['tmp_name'];
                    $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    
                    if($fileSize > 2 * 1024 * 1024){
                        echo json_encode(['status' => 'error', 'message' => 'File is too large.']);
                        exit;
                    }else if($fileExtension != 'mp4' && $fileExtension != 'mov'){
                        echo json_encode(['status' => 'error', 'message' => 'File extension must be mp4 or mov.']);
                        exit;
                    }else{
                        // Handle image
                        $uploadDir = '../client_media/videos';
                        $uniqueFileName = uniqid() . '-' . basename($fileName);
                        $uploadPath = $uploadDir . '/' . $uniqueFileName;
                
                        if (move_uploaded_file($fileTmp, $uploadPath)) {
                            $templateMediaContent[] = 'https://app.watify.io/client_media/videos/' . $uniqueFileName;
                        } else {
                            echo json_encode(['status' => 'error', 'message' => 'Failed to save uploaded video']);
                            exit;
                        }
                    }
                }else{
                    $templateMediaContent[] = null;
                }
            }
        }

        //Validate required fields
        $required_fields = [$templateName, $templateCategory, $templateLanguage, $templateType,  $templateBody];
        $field_names = ['templateName', 'templateCategory', 'templateLanguage', 'templateType', 'templateBody'];
    
        foreach ($required_fields as $index => $field) {
            if (empty($field)) {
                echo json_encode(['status' => 'error', 'message' => 'Missing field: ' . $field_names[$index]]);
                exit;
            }
        }

        $sql = "INSERT INTO client_templates(
            client_id, template_name, template_category, template_language, template_type, template_media_type, template_media_content, template_body, template_footer
        ) VALUES(
            '$clientId', '$templateName', '$templateCategory', '$templateLanguage', 
            '$templateType',null,null,'$templateBody','$templateFooter'
        )";
        
        if (!mysqli_query($db, $sql)) {
            echo json_encode(['status' => 'error', 'message' => mysqli_error($db)]);
            exit;
        }
        $templateId = mysqli_insert_id($db);
        $i=0;

        foreach($carouselData as $carouselKey=>$carouselVal){
            $carouselMediaType = mysqli_real_escape_string($db, $carouselVal['media_type']);
            $carouselMessage = mysqli_real_escape_string($db, $carouselVal['message']);
            $carouselMediaContent = isset($templateMediaContent[$i]) ? $templateMediaContent[$i] : null;

            $carouselSQL = "INSERT INTO template_carousels(
                template_id, carousel_media_type, carousel_media_content, carousel_card_content
            ) VALUES ('$templateId', '$carouselMediaType', " . ($carouselMediaContent ? "'$carouselMediaContent'" : "NULL") . ", '$carouselMessage');";

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

            $carouselId = mysqli_insert_id($db);

            foreach($carouselVal['buttons'] as $carBtnKey => $carBtnVal){            
                $buttonType = mysqli_real_escape_string($db, $carBtnVal['button_type'])??'';
                $buttonTitle = mysqli_real_escape_string($db, $carBtnVal['button_title']??'');

                if($buttonType == 'quickReply'){
                    $carouselBtnSQL = "INSERT INTO template_carousel_buttons(template_id, carousel_id, button_type, text, link_type, link)
                    VALUES('$templateId','$carouselId','$buttonType','$buttonTitle', null, null);";
                }else{
                    $linkType = mysqli_real_escape_string($db, $carBtnVal['link_type'])?? '';
                    $link = mysqli_real_escape_string($db, $carBtnVal['link'])?? '';
                    $carouselBtnSQL = "INSERT INTO template_carousel_buttons(template_id, carousel_id, button_type, text, link_type, link)
                    VALUES('$templateId','$carouselId','$buttonType','$buttonTitle', '$linkType', '$link');";
                }


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

        echo json_encode([
            'status' => 'success',
            'message' => 'Template saved successfully',
            'template_id' => $templateId,
        ]);
    }


    mysqli_close($db);