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

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));

    if (!isset($_POST['template_id']) || empty($_POST['template_id'])) {
        echo json_encode(['status' => 'error', 'message' => 'Something went wrong, Try again later!', 'reason' => 'template id is missing']);
        exit;
    }
    $template_id = $_POST['template_id'];
    $template_id = (int)$template_id; // sanitize

    try {

        mysqli_begin_transaction($db);

        $sql = "UPDATE client_templates 
            SET template_name = '$templateName', 
                template_category= '$templateCategory', 
                template_language= '$templateLanguage',
                template_type = '$templateType',
                template_media_type = '$templateMediaType',
                template_media_content = '$templateMediaContent',
                template_body = '$templateBody',
                copy_text = '$copyTextString',
                copy_code = '$copyCodeString',
                template_footer = '$templateFooter'
            WHERE id = $template_id and client_id = '$clientId'";

        if (!mysqli_query($db, $sql)) {
            throw new Exception("Failed to update template: ".mysqli_error($db));
            // echo json_encode(['status' => 'error', 'message' => mysqli_error($db)]);
            // exit;
        }


        // ✅ Handle structured buttons only
        $structuredButtons = json_decode($structuredButtonsRaw, true);

        if (is_array($structuredButtons) && count($structuredButtons)) {
            $sql = "SELECT id FROM template_buttons WHERE template_id = $template_id";
            $sql_result = mysqli_query($db, $sql);

            if (!$sql_result) {
                // echo json_encode(['status' => 'error', 'message' => mysqli_error($db)]);
                // exit;
                throw new Exception('Failed to fetch old buttons: ' . mysqli_error($db));
            }

            if (mysqli_num_rows($sql_result) != 0) {
                // Delete old buttons
                if (!mysqli_query($db, "DELETE FROM template_buttons WHERE template_id = $template_id")) {
                    throw new Exception('Failed to delete old buttons: ' . mysqli_error($db));
                }
            }

            // Insert new buttons (loop through new buttons here)
            foreach ($structuredButtons as $button) {
                $fieldType  = isset($button['field-type']) ? "'" . mysqli_real_escape_string($db, $button['field-type']) . "'" : "NULL";
                $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 ($template_id, $fieldType, $text, $linkType, $link, $number)";

                if (!mysqli_query($db, $btnSql)) {
                    throw new Exception('Button updation failed: ' . mysqli_error($db));
                }
            }

            mysqli_commit($db);
        }
    } catch (Exception $e) {
        mysqli_rollback($db); // Rollback if anything fails

        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        exit;
    }

    // ✅ Done
    echo json_encode([
        'status' => 'success',
        'message' => 'Template updated successfully',
    ]);
} else {
    $carouselData = '';

    if (!isset($_POST['templateCarouselData'])) {
        echo json_encode(['status' => 'error', 'message' => 'Missing Field: Carousel Data']);
        exit;
    }

    $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;
        }
    }
    if (!isset($_POST['template_id']) || empty($_POST['template_id'])) {
        echo json_encode(['status' => 'error', 'message' => 'Something went wrong, Try again later!', 'reason' => 'template id is missing']);
        exit;
    }
    $template_id = $_POST['template_id'];
    $template_id = (int)$template_id; // sanitize
    mysqli_begin_transaction($db);

    try {

        $sql = "UPDATE client_templates
            SET template_name = '$templateName', 
                template_category = '$templateCategory', 
                template_language = '$templateLanguage', 
                template_type = '$templateType',  
                template_body = '$templateBody', 
                template_footer = '$templateFooter'
            WHERE id = '$template_id' AND client_id = '$clientId'";

        if (!mysqli_query($db, $sql)) {
            throw new Exception("Failed to update carousel data: " . mysqli_error($db));
            // echo json_encode(['status' => 'error', 'message' => mysqli_error($db)]);
            // exit;
        }


        // firstly check carousel buttons exists or not before delete 
        $carousel_btn_query = "SELECT id FROM template_carousel_buttons WHERE template_id = '$template_id'";
        $carousel_btn_query_result = mysqli_query($db, $carousel_btn_query);
        if (!$carousel_btn_query_result) {
            throw new Exception('failed to fetch old carousel buttons: ' . mysqli_error($db));
        }
        if (mysqli_num_rows($carousel_btn_query_result) != 0) {
            // delete old carousels buttons
            $delete_old_car_btn_query = "DELETE FROM template_carousel_buttons WHERE template_id = '$template_id'";
            if (!mysqli_query($db, $delete_old_car_btn_query)) {
                throw new Exception('Failed to delete old carousel buttons: ' . mysqli_error($db));
            }
        }
        // delete old carousels
        $delete_old_car_query = "DELETE FROM template_carousels WHERE template_id = '$template_id'";
        if (!mysqli_query($db, $delete_old_car_query)) {
            throw new Exception('Failed to delete old carousels: ' . mysqli_error($db));
        }
        $i = 0;

        // Insert new carousel data
        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;
            if (isset($carouselVal['media_content'])) {
                if (str_starts_with($carouselVal['media_content'], 'blob:')) {
                    $carouselMediaContent = isset($templateMediaContent[$i]) ? $templateMediaContent[$i] : null;
                } else {
                    $carouselMediaContent = $carouselVal['media_content'];
                }
            } else {
                $carouselMediaContent = null;
            }
            // $carouselMediaContent = $carouselVal['media_content'] && !str_starts_with($carouselVal['media_content'], 'url("blob') ?$carouselVal['media_content']:(isset($templateMediaContent[$i]) ? $templateMediaContent[$i]:null );

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

            if (!mysqli_query($db, $carouselSQL)) {
                throw new Exception("Failed to insert new carousel data: " . mysqli_error($db));
                // echo json_encode(['status' => 'error', 'message' => mysqli_error($db)]);
                // exit;
            }

            $carouselId = mysqli_insert_id($db);
            if (isset($carouselVal['buttons']) && is_array($carouselVal['buttons'])) {
                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('$template_id','$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('$template_id','$carouselId','$buttonType','$buttonTitle', '$linkType', '$link');";
                    }


                    if (!mysqli_query($db, $carouselBtnSQL)) {
                        throw new Exception("Failed to insert new carousel buttons: " . mysqli_error($db));
                        // echo json_encode(['status' => 'error', 'message' => mysqli_error($db)]);
                        // exit;
                    }
                };
                $i++;
            }
        }
        mysqli_commit($db);
    } catch (Exception $e) {
        mysqli_rollback($db); // Rollback if anything fails

        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        exit;
    }

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