<?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']);

// ✅ Collect fields
$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'] ?? '');
$templateMediaType    = mysqli_real_escape_string($db, $_POST['templateMediatype'] ?? '');
$templateBody         = mysqli_real_escape_string($db, $_POST['templateBody'] ?? '');
$templateFooter       = mysqli_real_escape_string($db, $_POST['previewMessageFooterInput'] ?? '');
$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'] ?? '[]';
$quickReplyTextRaw    = $_POST['commaSeperatedvalue'] ?? ''; 

// ✅ 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) {
    $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 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));

// ✅ Handle quick replies
$quickReplyText = mysqli_real_escape_string($db, trim($quickReplyTextRaw));

// ✅ Insert into client_templates
$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, quick_reply_text
) VALUES (
    '$clientId', '$templateName', '$templateCategory', '$templateLanguage', 
    '$templateType', '$templateMediaType', '$templateMediaContent', 
    '$templateBody', '$templateFooter', '$copyTextString', '$copyCodeString', '$quickReplyText'
)";

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',
    'template_id' => $templateId,
    'image_url' => $templateMediaContent
]);
mysqli_close($db);
