<?php
/**
 * footer_extensions_logic.php - Handles backend processing for extended features
 */

// ১. লেআউট ও নিউজলেটার ডাটা
$column_layout = mysqli_real_escape_string($conn, $_POST['footer_columns'] ?? 4);
$newsletter_show = mysqli_real_escape_string($conn, $_POST['newsletter_status'] ?? 0);
$newsletter_title = mysqli_real_escape_string($conn, $_POST['newsletter_title'] ?? '');

// ২. সার্টিফিকেশন আইকন আপলোড হ্যান্ডলিং
$cert_data = [];
if(isset($_POST['cert_names'])){
    foreach($_POST['cert_names'] as $k => $name){
        $icon_path = $_POST['existing_cert_icons'][$k] ?? '';
        if(isset($_FILES['cert_files']['name'][$k]) && !empty($_FILES['cert_files']['name'][$k])){
            $target_dir = "uploads/footer/";
            if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);
            $file_name = time() . "_cert_" . basename($_FILES['cert_files']['name'][$k]);
            $target_file = $target_dir . $file_name;
            if(move_uploaded_file($_FILES['cert_files']['tmp_name'][$k], $target_file)){
                $icon_path = $target_file;
            }
        }
        if(!empty($name) || !empty($icon_path)){
            $cert_data[] = ['name' => $name, 'icon' => $icon_path];
        }
    }
}
$cert_json = json_encode($cert_data, JSON_UNESCAPED_UNICODE);

// ৩. পেমেন্ট মেথড আইকন আপলোড হ্যান্ডলিং
$pay_data = [];
if(isset($_POST['pay_names'])){
    foreach($_POST['pay_names'] as $k => $name){
        $icon_path = $_POST['existing_pay_icons'][$k] ?? '';
        if(isset($_FILES['pay_files']['name'][$k]) && !empty($_FILES['pay_files']['name'][$k])){
            $target_dir = "uploads/footer/";
            if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);
            $file_name = time() . "_pay_" . basename($_FILES['pay_files']['name'][$k]);
            $target_file = $target_dir . $file_name;
            if(move_uploaded_file($_FILES['pay_files']['tmp_name'][$k], $target_file)){
                $icon_path = $target_file;
            }
        }
        if(!empty($name) || !empty($icon_path)){
            $pay_data[] = ['name' => $name, 'icon' => $icon_path];
        }
    }
}
$pay_json = json_encode($pay_data, JSON_UNESCAPED_UNICODE);

// ডাটাবেস কোয়েরিতে এই ভেরিয়েবলগুলো যুক্ত করার জন্য মূল SQL আপডেট করা হয়েছে।
// নিশ্চিত করুন আপনার ডাটাবেসে এই কলামগুলো আছে: 
// column_layout, newsletter_show, newsletter_title, certifications, payment_icons
$sql_ext = ", column_layout = '$column_layout', 
             newsletter_show = '$newsletter_show', 
             newsletter_title = '$newsletter_title', 
             certifications = '$cert_json', 
             payment_icons = '$pay_json' ";

// মূল SQL ভেরিয়েবলে এটি যোগ করার কৌশল (admin_footer_settings.php এর SQL এর সাথে মার্জ হবে)
$sql = str_replace("WHERE id = 1", $sql_ext . " WHERE id = 1", $sql);