<?php
/**
 * admin_footer_settings.php - Handles footer content management
 * Updated with Company Logo Upload in Col 1
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once('db_config.php'); 

$current_user_role = isset($_SESSION['user_role']) ? $_SESSION['user_role'] : "Staff"; 
$is_admin = ($current_user_role === 'Admin' || $current_user_role === 'Super Admin');

$status_msg = "";
$tableName = "footer_settings";

// ডাটা আপডেট লজিক (শুধুমাত্র এডমিনদের জন্য)
if ($is_admin && isset($_POST['update_footer'])) {
    $about_text = mysqli_real_escape_string($conn, $_POST['about_text']);
    
    // Logo Upload Logic
    $logo_path = "";
    $fetch_old = mysqli_query($conn, "SELECT logo_url FROM $tableName WHERE id = 1");
    $old_data = mysqli_fetch_assoc($fetch_old);
    $logo_path = $old_data['logo_url'] ?? '';

    if (isset($_FILES['company_logo']) && $_FILES['company_logo']['error'] === 0) {
        $target_dir = "assets/files/logo/";
        if (!is_dir($target_dir)) {
            mkdir($target_dir, 0777, true);
        }
        
        $file_ext = pathinfo($_FILES["company_logo"]["name"], PATHINFO_EXTENSION);
        $file_name = "footer_logo_" . time() . "." . $file_ext;
        $target_file = $target_dir . $file_name;

        if (move_uploaded_file($_FILES["company_logo"]["tmp_name"], $target_file)) {
            $logo_path = $target_file;
        }
    }

    // Column Titles Processing
    $col1_title = mysqli_real_escape_string($conn, $_POST['col1_title']);
    $col2_title = mysqli_real_escape_string($conn, $_POST['col2_title']);
    $col3_title = mysqli_real_escape_string($conn, $_POST['col3_title']);
    $col4_title = mysqli_real_escape_string($conn, $_POST['col4_title']);
    
    // সোশ্যাল লিঙ্ক প্রোসেসিং
    $social_data = [];
    if(isset($_POST['social_names'])){
        foreach($_POST['social_names'] as $key => $name){
            if(!empty($name)){
                $social_data[] = [
                    'name' => mysqli_real_escape_string($conn, $name),
                    'icon' => mysqli_real_escape_string($conn, $_POST['social_icons'][$key]),
                    'link' => mysqli_real_escape_string($conn, $_POST['social_links'][$key])
                ];
            }
        }
    }
    $social_json = json_encode($social_data, JSON_UNESCAPED_UNICODE);
    
    // সার্ভিস লিঙ্ক প্রোসেসিং
    $services_data = [];
    if(isset($_POST['service_names'])){
        foreach($_POST['service_names'] as $key => $name){
            if(!empty($name)){
                $services_data[] = [
                    'name' => mysqli_real_escape_string($conn, $name),
                    'link' => mysqli_real_escape_string($conn, $_POST['service_links'][$key])
                ];
            }
        }
    }
    $services_json = json_encode($services_data, JSON_UNESCAPED_UNICODE);
    
    // কুইক লিঙ্ক প্রোসেসিং
    $quick_data = [];
    if(isset($_POST['quick_names'])){
        foreach($_POST['quick_names'] as $key => $name){
            if(!empty($name)){
                $quick_data[] = [
                    'name' => mysqli_real_escape_string($conn, $name),
                    'link' => mysqli_real_escape_string($conn, $_POST['quick_links'][$key])
                ];
            }
        }
    }
    $quick_json = json_encode($quick_data, JSON_UNESCAPED_UNICODE);
    
    // ডাইনামিক কন্টাক্ট প্রোসেসিং
    $contact_list = [];
    if(isset($_POST['office_labels'])){
        foreach($_POST['office_labels'] as $idx => $office_name){
            if(!empty($office_name)){
                $office_details = [];
                if(isset($_POST['office_items_type'][$idx])){
                    foreach($_POST['office_items_type'][$idx] as $item_idx => $type){
                        $office_details[] = [
                            'type'  => mysqli_real_escape_string($conn, $type),
                            'value' => mysqli_real_escape_string($conn, $_POST['office_items_value'][$idx][$item_idx]),
                            'link'  => mysqli_real_escape_string($conn, $_POST['office_items_link'][$idx][$item_idx])
                        ];
                    }
                }
                
                $contact_list[] = [
                    'label'   => mysqli_real_escape_string($conn, $office_name),
                    'address' => mysqli_real_escape_string($conn, $_POST['office_address'][$idx]),
                    'details' => $office_details
                ];
            }
        }
    }
    $contacts_json = json_encode($contact_list, JSON_UNESCAPED_UNICODE);

    // নিউজলেটার প্রোসেসিং
    $newsletter_status = isset($_POST['newsletter_enable']) ? 1 : 0;
    $newsletter_text = mysqli_real_escape_string($conn, $_POST['newsletter_text']);

    $copyright = mysqli_real_escape_string($conn, $_POST['copyright_text']);
    $dev_text = mysqli_real_escape_string($conn, $_POST['dev_text']);
    $dev_url = mysqli_real_escape_string($conn, $_POST['dev_url']);

    // SQL Update with Column Titles, Newsletter & Logo
    $sql = "UPDATE $tableName SET 
            logo_url = '$logo_path',
            about_text = '$about_text', 
            col1_title = '$col1_title',
            col2_title = '$col2_title',
            col3_title = '$col3_title',
            col4_title = '$col4_title',
            social_links = '$social_json', 
            services_links = '$services_json',
            quick_links = '$quick_json',
            phone = '$contacts_json', 
            newsletter_enable = '$newsletter_status',
            newsletter_text = '$newsletter_text',
            copyright_text = '$copyright', 
            dev_text = '$dev_text',
            dev_url = '$dev_url'
            WHERE id = 1";
    
    if(mysqli_query($conn, $sql)){
        $status_msg = "<div class='alert-success'><i class='fas fa-check-circle'></i> ফুটার সেটিংস সফলভাবে আপডেট করা হয়েছে!</div>";
    } else {
        $status_msg = "<div class='alert-danger'>Error: " . mysqli_error($conn) . "</div>";
    }
}

// ডাটা রিড
$fetch_query = mysqli_query($conn, "SELECT * FROM $tableName WHERE id = 1");
$footer = mysqli_fetch_assoc($fetch_query);

$saved_socials = json_decode($footer['social_links'] ?? '[]', true) ?: [];
$saved_services = json_decode($footer['services_links'] ?? '[]', true) ?: [];
$saved_quick_links = json_decode($footer['quick_links'] ?? '[]', true) ?: [];
$saved_contacts = json_decode($footer['phone'] ?? '[]', true) ?: []; 

$icon_options = [
    "" => "সিলেক্ট করুন",
    "fa-brands fa-facebook" => "Facebook",
    "fa-brands fa-whatsapp" => "WhatsApp",
    "fa-brands fa-youtube" => "YouTube",
    "fa-brands fa-instagram" => "Instagram",
    "fa-brands fa-x-twitter" => "X (Twitter)",
    "fa-brands fa-linkedin" => "LinkedIn",
    "fa-brands fa-telegram" => "Telegram"
];

$contact_type_icons = [
    "fa-solid fa-phone" => "ফোন নম্বর",
    "fa-solid fa-envelope" => "ইমেইল এড্রেস",
    "fa-brands fa-whatsapp" => "WhatsApp"
];
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Footer Settings | Admin Panel</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        :root {
            --primary-color: #2c3e50;
            --accent-color: #3498db;
            --success-color: #27ae60;
            --danger-color: #e74c3c;
            --warning-color: #f39c12;
            --bg-light: #f8fafc;
            --border-color: #e2e8f0;
        }

        body { 
            margin: 0; 
            font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; 
            color: #333;
        }

        .alert-success { background:#d4edda; color:#155724; padding:15px; border-radius:8px; margin-bottom:20px; border-left: 5px solid var(--success-color); font-weight: 500; }
        .alert-danger { background:#f8d7da; color:#721c24; padding:15px; border-radius:8px; margin-bottom:20px; border-left: 5px solid var(--danger-color); }
        .alert-info { background:#d1ecf1; color:#0c5460; padding:15px; border-radius:8px; margin-bottom:20px; border-left: 5px solid var(--accent-color); }

        .section-card { background: white; padding: 25px; border-radius: 12px; box-shadow: 0 5px 15px rgba(0,0,0,0.05); margin-bottom: 30px; border: 1px solid var(--border-color); }
        .section-title { margin: 0 0 20px 0; color: var(--primary-color); font-size: 1.2rem; display: flex; align-items: center; gap: 10px; border-bottom: 1px solid #eee; padding-bottom: 15px; }
        .section-title i { color: var(--accent-color); }

        .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        .form-group { margin-bottom: 15px; display: flex; flex-direction: column; }
        
        label { font-weight: 600; margin-bottom: 8px; color: #444; font-size: 14px; }
        .label-title { color: var(--accent-color); font-weight: 700; margin-bottom: 10px; background: #f0f7ff; padding: 8px; border-radius: 6px; }

        input, select, textarea { padding: 12px; border: 1px solid #ccc; border-radius: 8px; font-size: 14px; outline: none; transition: 0.3s; background: #fff; font-family: inherit; }
        input:focus, select:focus, textarea:focus { border-color: var(--accent-color); box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1); }

        .btn-save { background: var(--success-color); color: white; padding: 14px 25px; border: none; border-radius: 8px; font-weight: bold; cursor: pointer; transition: 0.3s; font-size: 16px; width: 100%; display: block; }
        .btn-save:hover { background: #219150; transform: translateY(-1px); }
        
        .btn-add { background: #fff; color: var(--accent-color); border: 2px dashed var(--accent-color); padding: 8px; border-radius: 8px; font-weight: 600; cursor: pointer; margin-top: 5px; transition: 0.2s; width: 100%; font-size: 13px; }
        .btn-add:hover { background: #f0f7ff; }

        .btn-remove { background: #fff; color: var(--danger-color); border: 1px solid #fee2e2; width: 35px; height: 35px; border-radius: 8px; cursor: pointer; transition: 0.2s; display: flex; align-items: center; justify-content: center; }
        .btn-remove:hover { background: var(--danger-color); color: white; }

        .office-card { background: #f9fbff; border: 1px solid #e1e8f0; padding: 20px; border-radius: 12px; margin-bottom: 20px; position: relative; }
        .office-remove { position: absolute; top: 10px; right: 10px; background: #fff; color: red; border: 1px solid #ffcccc; border-radius: 50%; width: 25px; height: 25px; cursor: pointer; }

        .item-row { display: grid; grid-template-columns: 130px 1fr 1fr auto; gap: 10px; margin-top: 8px; align-items: center; background: white; padding: 8px; border-radius: 8px; border: 1px inset #eee; }
        
        .dynamic-row { display: grid; grid-template-columns: 1fr 1fr 1.5fr auto; gap: 12px; background: #fcfcfc; padding: 10px; border-radius: 10px; border: 1px solid #f1f1f1; margin-bottom: 10px; align-items: center; }
        .badge-col { background: var(--primary-color); color: white; padding: 3px 8px; border-radius: 4px; font-size: 10px; text-transform: uppercase; margin-right: 5px; vertical-align: middle; }

        /* Logo Preview Style */
        .logo-preview-box { background: #f1f5f9; padding: 15px; border-radius: 10px; border: 1px dashed #cbd5e1; margin-bottom: 15px; display: flex; align-items: center; gap: 20px; }
        .logo-preview-box img { max-height: 60px; max-width: 150px; border-radius: 4px; }

        /* Newsletter Toggle Style */
        .switch { position: relative; display: inline-block; width: 50px; height: 24px; }
        .switch input { opacity: 0; width: 0; height: 0; }
        .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: .4s; border-radius: 24px; }
        .slider:before { position: absolute; content: ""; height: 18px; width: 18px; left: 4px; bottom: 3px; background-color: white; transition: .4s; border-radius: 50%; }
        input:checked + .slider { background-color: var(--accent-color); }
        input:checked + .slider:before { transform: translateX(24px); }

        @media (max-width: 768px) {
            .form-grid { grid-template-columns: 1fr; }
            .item-row { grid-template-columns: 1fr; }
            .dynamic-row { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>

<div>
    <?php if (!$is_admin): ?>
        <div class="alert-info">
            <i class="fas fa-info-circle"></i> আপনি বর্তমানে <strong><?php echo $current_user_role; ?></strong> হিসেবে লগইন আছেন। আপনার তথ্য পরিবর্তন করার অনুমতি নেই।
        </div>
    <?php endif; ?>

    <h2 style="margin: 0px 0px 15px 0px; font-weight: 800; color: var(--primary-color);">
        <i class="fas fa-tools"></i> ফুটার ম্যানেজমেন্ট
    </h2>

    <?php echo $status_msg; ?>

    <form method="POST" enctype="multipart/form-data">
        
        <!-- Column 1: About & Social -->
        <div class="section-card">
            <h3 class="section-title"><span class="badge-col">Col 1</span> কলাম ১: আমাদের সম্পর্কে ও সোশ্যাল</h3>
            
            <div class="form-grid">
                <div class="form-group">
                    <label class="label-title">কোম্পানি লোগো (Footer Logo)</label>
                    <div class="logo-preview-box">
                        <?php if(!empty($footer['logo_url'])): ?>
                            <img src="<?php echo $footer['logo_url']; ?>" alt="Logo">
                        <?php else: ?>
                            <div style="font-size: 12px; color: #64748b;">কোন লোগো আপলোড করা নেই</div>
                        <?php endif; ?>
                        <div style="flex:1;">
                            <input type="file" name="company_logo" accept="image/*" style="padding: 5px; border: none; font-size: 12px;">
                            <small style="color: #64748b; display: block; margin-top: 5px;">* প্যাথ: assets/img/logo (PNG/JPG)</small>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label class="label-title">কলাম টাইটেল (Title)</label>
                    <input type="text" name="col1_title" value="<?php echo $footer['col1_title'] ?? 'আমাদের সম্পর্কে'; ?>" placeholder="উদা: আমাদের সম্পর্কে">
                </div>
            </div>

            <div class="form-group">
                <label>সংক্ষিপ্ত বর্ণনা (About Us Text)</label>
                <textarea name="about_text" rows="3" placeholder="ফুটারের প্রথম কলামে দেখানোর জন্য বর্ণনা লিখুন..."><?php echo $footer['about_text'] ?? ''; ?></textarea>
            </div>

            <div style="margin-top: 25px;">
                <label>সোশ্যাল প্রোফাইল লিঙ্কসমূহ</label>
                <div id="social-container">
                    <?php if(!empty($saved_socials)): foreach($saved_socials as $social): ?>
                    <div class="dynamic-row">
                        <input type="text" name="social_names[]" value="<?php echo $social['name'] ?? ''; ?>" placeholder="নাম (উদা: Facebook)">
                        <select onchange="updateIconValue(this)">
                            <?php foreach($icon_options as $class => $label): ?>
                                <option value="<?php echo $class; ?>" <?php echo (($social['icon'] ?? '') == $class) ? 'selected' : ''; ?>><?php echo $label; ?></option>
                            <?php endforeach; ?>
                        </select>
                        <input type="hidden" name="social_icons[]" value="<?php echo $social['icon'] ?? ''; ?>">
                        <input type="text" name="social_links[]" value="<?php echo $social['link'] ?? ''; ?>" placeholder="লিঙ্ক (https://...)">
                        <button type="button" class="btn-remove" onclick="this.parentElement.remove()"><i class="fas fa-trash"></i></button>
                    </div>
                    <?php endforeach; endif; ?>
                </div>
                <button type="button" class="btn-add" onclick="addSocialRow()"><i class="fas fa-plus"></i> নতুন সোশ্যাল লিঙ্ক যোগ করুন</button>
            </div>
        </div>

        <div class="form-grid">
            <!-- Column 2: Services -->
            <div class="section-card">
                <h3 class="section-title"><span class="badge-col">Col 2</span> কলাম ২: সার্ভিসসমূহ</h3>
                
                <div class="form-group">
                    <label class="label-title">কলাম টাইটেল (Title)</label>
                    <input type="text" name="col2_title" value="<?php echo $footer['col2_title'] ?? 'আমাদের সার্ভিসসমূহ'; ?>" placeholder="উদা: আমাদের সেবা">
                </div>

                <div id="services-container">
                    <?php if(!empty($saved_services)): foreach($saved_services as $service): ?>
                    <div class="dynamic-row" style="grid-template-columns: 1fr 1.5fr auto;">
                        <input type="text" name="service_names[]" value="<?php echo $service['name'] ?? ''; ?>" placeholder="সার্ভিস নাম">
                        <input type="text" name="service_links[]" value="<?php echo $service['link'] ?? ''; ?>" placeholder="লিঙ্ক">
                        <button type="button" class="btn-remove" onclick="this.parentElement.remove()"><i class="fas fa-times"></i></button>
                    </div>
                    <?php endforeach; endif; ?>
                </div>
                <button type="button" class="btn-add" onclick="addRow('services-container', 'service_names[]', 'service_links[]')"><i class="fas fa-plus"></i> যোগ করুন</button>
            </div>

            <!-- Column 3: Quick Links -->
            <div class="section-card">
                <h3 class="section-title"><span class="badge-col">Col 3</span> কলাম ৩: কুইক লিঙ্কসমূহ</h3>
                
                <div class="form-group">
                    <label class="label-title">কলাম টাইটেল (Title)</label>
                    <input type="text" name="col3_title" value="<?php echo $footer['col3_title'] ?? 'কুইক লিঙ্কসমূহ'; ?>" placeholder="উদা: গুরুত্বপূর্ণ লিঙ্ক">
                </div>

                <div id="quick-container">
                    <?php if(!empty($saved_quick_links)): foreach($saved_quick_links as $quick): ?>
                    <div class="dynamic-row" style="grid-template-columns: 1fr 1.5fr auto;">
                        <input type="text" name="quick_names[]" value="<?php echo $quick['name'] ?? ''; ?>" placeholder="পেজ নাম">
                        <input type="text" name="quick_links[]" value="<?php echo $quick['link'] ?? ''; ?>" placeholder="লিঙ্ক">
                        <button type="button" class="btn-remove" onclick="this.parentElement.remove()"><i class="fas fa-times"></i></button>
                    </div>
                    <?php endforeach; endif; ?>
                </div>
                <button type="button" class="btn-add" onclick="addRow('quick-container', 'quick_names[]', 'quick_links[]')"><i class="fas fa-plus"></i> যোগ করুন</button>
            </div>
        </div>

        <!-- Column 4: Enhanced Multi-Contact Contact & Newsletter -->
        <div class="section-card">
            <h3 class="section-title"><span class="badge-col">Col 4</span> কলাম ৪: যোগাযোগ তথ্য ও নিউজলেটার</h3>
            
            <div class="form-group">
                <label class="label-title">কলাম টাইটেল (Title)</label>
                <input type="text" name="col4_title" value="<?php echo $footer['col4_title'] ?? 'যোগাযোগ করুন'; ?>" placeholder="উদা: আমাদের ঠিকানা">
            </div>

            <div id="office-container">
                <?php if(!empty($saved_contacts)): foreach($saved_contacts as $idx => $office): ?>
                <div class="office-card" id="office-row-<?php echo $idx; ?>">
                    <button type="button" class="office-remove" onclick="this.parentElement.remove()">&times;</button>
                    <div class="form-grid" style="grid-template-columns: 1fr 2fr; margin-bottom: 10px;">
                        <div class="form-group">
                            <label>অফিসের নাম/লেবেল</label>
                            <input type="text" name="office_labels[]" value="<?php echo $office['label'] ?? ''; ?>" placeholder="উদা: হেড অফিস">
                        </div>
                        <div class="form-group">
                            <label>পুরো ঠিকানা</label>
                            <input type="text" name="office_address[]" value="<?php echo $office['address'] ?? ''; ?>" placeholder="রাস্তা, এলাকা, শহর">
                        </div>
                    </div>
                    
                    <label style="font-size: 12px; color: #666;">ফোন ও ইমেইলসমূহ:</label>
                    <div class="items-list">
                        <?php if(!empty($office['details'])): foreach($office['details'] as $item): ?>
                        <div class="item-row">
                            <select name="office_items_type[<?php echo $idx; ?>][]">
                                <?php foreach($contact_type_icons as $icon => $label): ?>
                                    <option value="<?php echo $icon; ?>" <?php echo (($item['type'] ?? '') == $icon) ? 'selected' : ''; ?>><?php echo $label; ?></option>
                                <?php endforeach; ?>
                            </select>
                            <input type="text" name="office_items_value[<?php echo $idx; ?>][]" value="<?php echo $item['value'] ?? ''; ?>" placeholder="নম্বর/ইমেইল">
                            <input type="text" name="office_items_link[<?php echo $idx; ?>][]" value="<?php echo $item['link'] ?? ''; ?>" placeholder="লিঙ্ক (tel:.. / mailto:..)">
                            <button type="button" class="btn-remove" onclick="this.parentElement.remove()"><i class="fas fa-trash-alt"></i></button>
                        </div>
                        <?php endforeach; endif; ?>
                    </div>
                    <button type="button" class="btn-add" onclick="addOfficeItem(<?php echo $idx; ?>)" style="width: auto; padding: 5px 15px; border-style: solid; margin-top: 10px;">
                        <i class="fas fa-plus"></i> ফোন/ইমেইল যোগ করুন
                    </button>
                </div>
                <?php endforeach; endif; ?>
            </div>
            <button type="button" class="btn-add" onclick="addNewOffice()" style="border-style: solid; border-width: 1px; background: #edf2f7; color: #2d3748; margin-bottom: 25px;">
                <i class="fas fa-building"></i> নতুন অফিস/ব্রাঞ্চ যোগ করুন
            </button>

            <!-- Newsletter Settings Sub-section -->
            <div style="background: #fff8f1; border: 1px solid #ffe4cc; padding: 20px; border-radius: 12px; margin-top: 20px;">
                <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 15px;">
                    <label style="color: #c05621; font-weight: 700; margin-bottom: 0;">
                        <i class="fas fa-paper-plane"></i> নিউজলেটার সাবস্ক্রিপশন ফর্ম
                    </label>
                    <label class="switch">
                        <input type="checkbox" name="newsletter_enable" <?php echo (($footer['newsletter_enable'] ?? 0) == 1) ? 'checked' : ''; ?>>
                        <span class="slider"></span>
                    </label>
                </div>
                <div class="form-group">
                    <label style="font-size: 13px;">নিউজলেটার টেক্সট (Short Instruction)</label>
                    <input type="text" name="newsletter_text" value="<?php echo $footer['newsletter_text'] ?? 'আমাদের সর্বশেষ আপডেট পেতে সাবস্ক্রাইব করুন।'; ?>" placeholder="উদা: সাবস্ক্রাইব করুন">
                </div>
                <small style="color: #718096; font-style: italic;">* এটি এনাবল করলে চতুর্থ কলামের নিচে ইমেইল সাবস্ক্রিপশন বক্স দেখাবে।</small>
            </div>
        </div>

        <!-- Copyright & Developer -->
        <div class="section-card">
            <h3 class="section-title"><i class="fas fa-copyright"></i> কপিরাইট এবং ডেভেলপার তথ্য</h3>
            <div class="form-grid">
                <div class="form-group">
                    <label>কপিরাইট টেক্সট (HTML সমর্থিত)</label>
                    <textarea name="copyright_text" rows="2" placeholder="© 2024 Your Brand"><?php echo $footer['copyright_text'] ?? ''; ?></textarea>
                </div>
                <div class="form-group">
                    <label>ডেভেলপার ক্রেডিট (Name & Link - HTML সমর্থিত)</label>
                    <div style="display: flex; gap: 8px;">
                        <textarea name="dev_text" rows="2" placeholder="Dev Name" style="flex:1;"><?php echo $footer['dev_text'] ?? ''; ?></textarea>
                        <textarea name="dev_url" rows="2" placeholder="Link" style="flex:1;"><?php echo $footer['dev_url'] ?? ''; ?></textarea>
                    </div>
                </div>
            </div>
        </div>

        <?php if ($is_admin): ?>
        <button type="submit" name="update_footer" class="btn-save">
            <i class="fas fa-save"></i> ফুটার সেটিংস সেভ করুন
        </button>
        <?php endif; ?>

    </form>
</div>

<script>
    // Fix: Default to 0 if saved_contacts is not an array or empty
    let officeCount = <?php echo is_array($saved_contacts) ? count($saved_contacts) : 0; ?>;

    function updateIconValue(select) {
        const row = select.closest('.dynamic-row');
        const hiddenInput = row.querySelector('input[name="social_icons[]"]');
        const nameInput = row.querySelector('input[name="social_names[]"]');
        hiddenInput.value = select.value;
        if(nameInput.value === "" && select.value !== "") {
            nameInput.value = select.options[select.selectedIndex].text;
        }
    }

    function addSocialRow() {
        const container = document.getElementById('social-container');
        const div = document.createElement('div');
        div.className = 'dynamic-row';
        div.innerHTML = `
            <input type="text" name="social_names[]" placeholder="নাম">
            <select onchange="updateIconValue(this)">
                <?php foreach($icon_options as $class => $label): ?>
                    <option value="<?php echo $class; ?>"><?php echo $label; ?></option>
                <?php endforeach; ?>
            </select>
            <input type="hidden" name="social_icons[]">
            <input type="text" name="social_links[]" placeholder="লিঙ্ক">
            <button type="button" class="btn-remove" onclick="this.parentElement.remove()"><i class="fas fa-trash"></i></button>
        `;
        container.appendChild(div);
    }

    function addRow(containerId, nameIn, linkIn) {
        const container = document.getElementById(containerId);
        const div = document.createElement('div');
        div.className = 'dynamic-row';
        div.style.cssText = 'grid-template-columns: 1fr 1.5fr auto;';
        div.innerHTML = `
            <input type="text" name="${nameIn}" placeholder="নাম">
            <input type="text" name="${linkIn}" placeholder="লিঙ্ক">
            <button type="button" class="btn-remove" onclick="this.parentElement.remove()"><i class="fas fa-times"></i></button>
        `;
        container.appendChild(div);
    }

    function addNewOffice() {
        const container = document.getElementById('office-container');
        const idx = officeCount++;
        const div = document.createElement('div');
        div.className = 'office-card';
        div.id = `office-row-${idx}`;
        div.innerHTML = `
            <button type="button" class="office-remove" onclick="this.parentElement.remove()">&times;</button>
            <div class="form-grid" style="grid-template-columns: 1fr 2fr; margin-bottom: 10px;">
                <div class="form-group">
                    <label>অফিসের নাম/লেবেল</label>
                    <input type="text" name="office_labels[]" placeholder="উদা: ঢাকা অফিস">
                </div>
                <div class="form-group">
                    <label>পুরো ঠিকানা</label>
                    <input type="text" name="office_address[]" placeholder="ঠিকানা লিখুন">
                </div>
            </div>
            <label style="font-size: 12px; color: #666;">ফোন ও ইমেইলসমূহ:</label>
            <div class="items-list"></div>
            <button type="button" class="btn-add" onclick="addOfficeItem(${idx})" style="width: auto; padding: 5px 15px; border-style: solid; margin-top: 10px;">
                <i class="fas fa-plus"></i> ফোন/ইমেইল যোগ করুন
            </button>
        `;
        container.appendChild(div);
        addOfficeItem(idx); // ডিফল্ট একটি আইটেম যোগ করা
    }

    function addOfficeItem(officeIdx) {
        const officeCard = document.getElementById(`office-row-${officeIdx}`);
        if (!officeCard) return;
        const list = officeCard.querySelector('.items-list');
        const div = document.createElement('div');
        div.className = 'item-row';
        div.innerHTML = `
            <select name="office_items_type[${officeIdx}][]">
                <?php foreach($contact_type_icons as $icon => $label): ?>
                    <option value="<?php echo $icon; ?>"><?php echo $label; ?></option>
                <?php endforeach; ?>
            </select>
            <input type="text" name="office_items_value[${officeIdx}][]" placeholder="নম্বর/ইমেইল">
            <input type="text" name="office_items_link[${officeIdx}][]" placeholder="লিঙ্ক (tel/mailto)">
            <button type="button" class="btn-remove" onclick="this.parentElement.remove()"><i class="fas fa-trash-alt"></i></button>
        `;
        list.appendChild(div);
    }
</script>

</body>
</html>