<?php
// ============================================
// ESC AL - Admin Dashboard (Dark Theme)
// ============================================
require_once 'config.php';
requireLogin();

$message = '';
$messageType = '';

// Handle all POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    // ============ UPLOAD SITE LOGO ============
    if ($action === 'upload_logo') {
        if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
            $oldLogo = getSiteLogo();
            if (!empty($oldLogo) && file_exists($oldLogo)) {
                deleteUploadedFile($oldLogo);
            }
            $upload = uploadFile($_FILES['logo'], 'logo', 'logo_');
            if ($upload['success']) {
                updateSiteLogo($upload['path']);
                $message = 'Logo uploaded successfully!';
                $messageType = 'success';
            } else {
                $message = $upload['error'];
                $messageType = 'error';
            }
        }
    }
    
    // ============ UPDATE LOGO SIZE ============
    if ($action === 'update_logo_size') {
        updateSetting('logo_size', $_POST['logo_size'], 'en');
        $message = 'Logo size updated!';
        $messageType = 'success';
    }
    
    // ============ UPLOAD FOOTER LOGO ============
    if ($action === 'upload_footer_logo') {
        if (isset($_FILES['footer_logo']) && $_FILES['footer_logo']['error'] === UPLOAD_ERR_OK) {
            $oldLogo = getFooterLogo();
            if (!empty($oldLogo) && file_exists($oldLogo)) {
                deleteUploadedFile($oldLogo);
            }
            $upload = uploadFile($_FILES['footer_logo'], 'logo', 'footer_');
            if ($upload['success']) {
                updateFooterLogo($upload['path']);
                $message = 'Footer logo uploaded!';
                $messageType = 'success';
            } else {
                $message = $upload['error'];
                $messageType = 'error';
            }
        }
    }
    
    // ============ UPDATE FOOTER LOGO SIZE ============
    if ($action === 'update_footer_logo_size') {
        updateSetting('footer_logo_size', $_POST['footer_logo_size'], 'en');
        $message = 'Footer logo size updated!';
        $messageType = 'success';
    }
    
    // ============ REMOVE LOGOS ============
    if ($action === 'remove_logo') {
        $oldLogo = getSiteLogo();
        if (!empty($oldLogo) && file_exists($oldLogo)) {
            deleteUploadedFile($oldLogo);
        }
        updateSiteLogo('');
        $message = 'Logo removed!';
        $messageType = 'success';
    }
    
    if ($action === 'remove_footer_logo') {
        $oldLogo = getFooterLogo();
        if (!empty($oldLogo) && file_exists($oldLogo)) {
            deleteUploadedFile($oldLogo);
        }
        updateFooterLogo('');
        $message = 'Footer logo removed!';
        $messageType = 'success';
    }
    
    // ============ UPLOAD HERO BACKGROUND ============
    if ($action === 'upload_hero_bg') {
        if (isset($_FILES['hero_bg']) && $_FILES['hero_bg']['error'] === UPLOAD_ERR_OK) {
            $oldBg = getHeroBackground();
            if (!empty($oldBg) && file_exists($oldBg)) {
                deleteUploadedFile($oldBg);
            }
            $upload = uploadFile($_FILES['hero_bg'], 'hero', 'hero_');
            if ($upload['success']) {
                updateHeroBackground($upload['path']);
                $message = 'Hero background uploaded!';
                $messageType = 'success';
            } else {
                $message = $upload['error'];
                $messageType = 'error';
            }
        }
    }
    
    if ($action === 'remove_hero_bg') {
        $oldBg = getHeroBackground();
        if (!empty($oldBg) && file_exists($oldBg)) {
            deleteUploadedFile($oldBg);
        }
        updateHeroBackground('');
        $message = 'Hero background removed!';
        $messageType = 'success';
    }
    
    // ============ ADD SERVICE ============
    if ($action === 'add_service') {
        $imagePath = '';
        if (isset($_FILES['service_image']) && $_FILES['service_image']['error'] === UPLOAD_ERR_OK) {
            $upload = uploadFile($_FILES['service_image'], 'services', 'svc_');
            if ($upload['success']) {
                $imagePath = $upload['path'];
            }
        }
        
        $stmt = $pdo->prepare("INSERT INTO services (icon, image, title_en, title_it, description_en, description_it, tags, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $_POST['icon'] ?? '🚀',
            $imagePath,
            $_POST['title_en'],
            $_POST['title_it'],
            $_POST['description_en'],
            $_POST['description_it'],
            $_POST['tags'],
            $_POST['sort_order'] ?? 0
        ]);
        $message = 'Service added!';
        $messageType = 'success';
    }
    
    // ============ UPDATE SERVICE ============
    if ($action === 'update_service') {
        $imagePath = $_POST['existing_image'] ?? '';
        
        if (isset($_FILES['service_image']) && $_FILES['service_image']['error'] === UPLOAD_ERR_OK) {
            if (!empty($imagePath) && file_exists($imagePath)) {
                deleteUploadedFile($imagePath);
            }
            $upload = uploadFile($_FILES['service_image'], 'services', 'svc_');
            if ($upload['success']) {
                $imagePath = $upload['path'];
            }
        }
        
        $stmt = $pdo->prepare("UPDATE services SET icon=?, image=?, title_en=?, title_it=?, description_en=?, description_it=?, tags=?, sort_order=?, is_active=? WHERE id=?");
        $stmt->execute([
            $_POST['icon'] ?? '🚀',
            $imagePath,
            $_POST['title_en'],
            $_POST['title_it'],
            $_POST['description_en'],
            $_POST['description_it'],
            $_POST['tags'],
            $_POST['sort_order'] ?? 0,
            $_POST['is_active'] ?? 1,
            $_POST['id']
        ]);
        $message = 'Service updated!';
        $messageType = 'success';
    }
    
    // ============ DELETE SERVICE ============
    if ($action === 'delete_service') {
        $stmt = $pdo->prepare("SELECT image FROM services WHERE id = ?");
        $stmt->execute([$_POST['id']]);
        $service = $stmt->fetch();
        if ($service && !empty($service['image']) && file_exists($service['image'])) {
            deleteUploadedFile($service['image']);
        }
        $stmt = $pdo->prepare("DELETE FROM services WHERE id = ?");
        $stmt->execute([$_POST['id']]);
        $message = 'Service deleted!';
        $messageType = 'success';
    }
    
    // ============ ADD PROJECT ============
    if ($action === 'add_project') {
        $imagePath = '';
        if (isset($_FILES['project_image']) && $_FILES['project_image']['error'] === UPLOAD_ERR_OK) {
            $upload = uploadFile($_FILES['project_image'], 'projects', 'proj_');
            if ($upload['success']) {
                $imagePath = $upload['path'];
            }
        }
        
        $stmt = $pdo->prepare("INSERT INTO projects (category_en, category_it, title_en, title_it, description_en, description_it, icon, image, bg_class, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $_POST['category_en'],
            $_POST['category_it'],
            $_POST['title_en'],
            $_POST['title_it'],
            $_POST['description_en'],
            $_POST['description_it'],
            $_POST['icon'] ?? '🏢',
            $imagePath,
            $_POST['bg_class'] ?? 'p1',
            $_POST['sort_order'] ?? 0
        ]);
        $message = 'Project added!';
        $messageType = 'success';
    }
    
    // ============ UPDATE PROJECT ============
    if ($action === 'update_project') {
        $imagePath = $_POST['existing_image'] ?? '';
        
        if (isset($_FILES['project_image']) && $_FILES['project_image']['error'] === UPLOAD_ERR_OK) {
            if (!empty($imagePath) && file_exists($imagePath)) {
                deleteUploadedFile($imagePath);
            }
            $upload = uploadFile($_FILES['project_image'], 'projects', 'proj_');
            if ($upload['success']) {
                $imagePath = $upload['path'];
            }
        }
        
        $stmt = $pdo->prepare("UPDATE projects SET category_en=?, category_it=?, title_en=?, title_it=?, description_en=?, description_it=?, icon=?, image=?, bg_class=?, sort_order=?, is_active=? WHERE id=?");
        $stmt->execute([
            $_POST['category_en'],
            $_POST['category_it'],
            $_POST['title_en'],
            $_POST['title_it'],
            $_POST['description_en'],
            $_POST['description_it'],
            $_POST['icon'] ?? '🏢',
            $imagePath,
            $_POST['bg_class'] ?? 'p1',
            $_POST['sort_order'] ?? 0,
            $_POST['is_active'] ?? 1,
            $_POST['id']
        ]);
        $message = 'Project updated!';
        $messageType = 'success';
    }
    
    // ============ DELETE PROJECT ============
    if ($action === 'delete_project') {
        $stmt = $pdo->prepare("SELECT image FROM projects WHERE id = ?");
        $stmt->execute([$_POST['id']]);
        $project = $stmt->fetch();
        if ($project && !empty($project['image']) && file_exists($project['image'])) {
            deleteUploadedFile($project['image']);
        }
        $stmt = $pdo->prepare("DELETE FROM projects WHERE id = ?");
        $stmt->execute([$_POST['id']]);
        $message = 'Project deleted!';
        $messageType = 'success';
    }
    
    // ============ UPDATE HOMEPAGE SETTINGS ============
    if ($action === 'update_settings') {
        $lang = $_POST['lang'] ?? 'en';
        $fields = [
            'site_title', 'hero_eyebrow', 'hero_title_line1', 'hero_title_line2',
            'hero_subtitle', 'hero_cta_primary', 'hero_cta_secondary',
            'stat1_num', 'stat1_label', 'stat2_num', 'stat2_label',
            'stat3_num', 'stat3_label', 'stat4_num', 'stat4_label',
            'services_section_label', 'services_title', 'services_desc',
            'portfolio_section_label', 'portfolio_title', 'portfolio_desc',
            'why_section_label', 'why_title', 'why_desc',
            'contact_section_label', 'contact_title', 'contact_desc',
            'contact_email', 'contact_phone', 'contact_location', 'contact_support',
            'footer_copyright'
        ];
        foreach ($fields as $field) {
            if (isset($_POST[$field])) {
                updateSetting($field, $_POST[$field], $lang);
            }
        }
        $message = 'Settings saved!';
        $messageType = 'success';
    }
    
    // ============ UPDATE CONTACT ICONS ============
    if ($action === 'update_contact_icons') {
        $icons = ['email_icon', 'phone_icon', 'location_icon', 'support_icon'];
        foreach ($icons as $icon) {
            if (isset($_POST[$icon])) {
                updateContactIcon($icon, $_POST[$icon]);
            }
        }
        
        foreach ($icons as $icon) {
            $fileKey = $icon . '_file';
            if (isset($_FILES[$fileKey]) && $_FILES[$fileKey]['error'] === UPLOAD_ERR_OK) {
                $upload = uploadFile($_FILES[$fileKey], 'contact', $icon . '_');
                if ($upload['success']) {
                    updateContactIcon($icon, $upload['path']);
                }
            }
        }
        
        $message = 'Contact icons updated!';
        $messageType = 'success';
    }
    
    // ============ MARK MESSAGE READ ============
    if ($action === 'mark_read') {
        $stmt = $pdo->prepare("UPDATE messages SET is_read = 1 WHERE id = ?");
        $stmt->execute([$_POST['id']]);
        $message = 'Message marked as read!';
        $messageType = 'success';
    }
    
    // ============ DELETE MESSAGE ============
    if ($action === 'delete_message') {
        $stmt = $pdo->prepare("DELETE FROM messages WHERE id = ?");
        $stmt->execute([$_POST['id']]);
        $message = 'Message deleted!';
        $messageType = 'success';
    }
    
    // ============ UPDATE WHY ITEM ============
    if ($action === 'update_why') {
        $imagePath = $_POST['existing_image'] ?? '';
        
        if (isset($_FILES['why_image']) && $_FILES['why_image']['error'] === UPLOAD_ERR_OK) {
            if (!empty($imagePath) && file_exists($imagePath)) {
                deleteUploadedFile($imagePath);
            }
            $upload = uploadFile($_FILES['why_image'], 'why', 'why_');
            if ($upload['success']) {
                $imagePath = $upload['path'];
            }
        }
        
        $stmt = $pdo->prepare("UPDATE why_items SET icon=?, image=?, title_en=?, title_it=?, description_en=?, description_it=?, sort_order=?, is_active=? WHERE id=?");
        $stmt->execute([
            $_POST['icon'] ?? '🎯',
            $imagePath,
            $_POST['title_en'],
            $_POST['title_it'],
            $_POST['description_en'],
            $_POST['description_it'],
            $_POST['sort_order'] ?? 0,
            $_POST['is_active'] ?? 1,
            $_POST['id']
        ]);
        $message = 'Why item updated!';
        $messageType = 'success';
    }
    
    // ============ CHANGE PASSWORD ============
    if ($action === 'change_password') {
        $currentPassword = $_POST['current_password'] ?? '';
        $newPassword = $_POST['new_password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';
        
        if ($newPassword !== $confirmPassword) {
            $message = 'Passwords do not match!';
            $messageType = 'error';
        } elseif (strlen($newPassword) < 6) {
            $message = 'Password must be at least 6 characters!';
            $messageType = 'error';
        } else {
            $stmt = $pdo->prepare("SELECT password FROM admins WHERE id = ?");
            $stmt->execute([$_SESSION['admin_id']]);
            $admin = $stmt->fetch();
            
            if (password_verify($currentPassword, $admin['password'])) {
                $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("UPDATE admins SET password = ? WHERE id = ?");
                $stmt->execute([$hashedPassword, $_SESSION['admin_id']]);
                $message = 'Password changed!';
                $messageType = 'success';
            } else {
                $message = 'Current password is incorrect!';
                $messageType = 'error';
            }
        }
    }
}

// Get current tab
$tab = $_GET['tab'] ?? 'dashboard';

// Fetch data
$unreadMessages = $pdo->query("SELECT COUNT(*) FROM messages WHERE is_read = 0")->fetchColumn();
$totalProjects = $pdo->query("SELECT COUNT(*) FROM projects")->fetchColumn();
$totalServices = $pdo->query("SELECT COUNT(*) FROM services")->fetchColumn();
$totalMessages = $pdo->query("SELECT COUNT(*) FROM messages")->fetchColumn();

$allServices = $pdo->query("SELECT * FROM services ORDER BY sort_order ASC")->fetchAll();
$allProjects = $pdo->query("SELECT * FROM projects ORDER BY sort_order ASC")->fetchAll();
$allMessages = $pdo->query("SELECT * FROM messages ORDER BY created_at DESC")->fetchAll();
$allWhyItems = $pdo->query("SELECT * FROM why_items ORDER BY sort_order ASC")->fetchAll();

$settingsEN = getAllSettings('en');
$settingsIT = getAllSettings('it');
$siteLogo = getSiteLogo();
$footerLogo = getFooterLogo();
$heroBg = getHeroBackground();
$contactIcons = getContactIcons();

// Get logo sizes
$logoSize = getSetting('logo_size', 'en');
if (empty($logoSize)) $logoSize = '40';
$footerLogoSize = getSetting('footer_logo_size', 'en');
if (empty($footerLogoSize)) $footerLogoSize = '35';

$bgClasses = ['p1', 'p2', 'p3', 'p4', 'p5', 'p6'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Dashboard - ESC.al</title>
<link href="https://fonts.googleapis.com/css2?family=Syne:wght@400;600;700;800&family=DM+Sans:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="dashboard.css">
</head>
<body>

<div class="admin-container">
  <!-- Sidebar -->
  <aside class="sidebar">
    <div class="sidebar-header">
      <h2>ESC.al</h2>
      <p>Admin Panel</p>
    </div>
    <ul class="sidebar-nav">
      <li><a href="?tab=dashboard" class="<?php echo $tab == 'dashboard' ? 'active' : ''; ?>">Dashboard</a></li>
      <li><a href="?tab=logo" class="<?php echo $tab == 'logo' ? 'active' : ''; ?>">Site Logos</a></li>
      <li><a href="?tab=hero" class="<?php echo $tab == 'hero' ? 'active' : ''; ?>">Hero Background</a></li>
      <li><a href="?tab=settings" class="<?php echo $tab == 'settings' ? 'active' : ''; ?>">Content Settings</a></li>
      <li><a href="?tab=contact_icons" class="<?php echo $tab == 'contact_icons' ? 'active' : ''; ?>">Contact Icons</a></li>
      <li><a href="?tab=services" class="<?php echo $tab == 'services' ? 'active' : ''; ?>">Services</a></li>
      <li><a href="?tab=projects" class="<?php echo $tab == 'projects' ? 'active' : ''; ?>">Projects</a></li>
      <li><a href="?tab=why" class="<?php echo $tab == 'why' ? 'active' : ''; ?>">Why Us</a></li>
      <li><a href="?tab=messages" class="<?php echo $tab == 'messages' ? 'active' : ''; ?>">Messages <?php if ($unreadMessages > 0): ?><span class="badge"><?php echo $unreadMessages; ?></span><?php endif; ?></a></li>
      <li><a href="?tab=password" class="<?php echo $tab == 'password' ? 'active' : ''; ?>">Change Password</a></li>
    </ul>
    <div class="sidebar-footer">
      <a href="index.php" target="_blank">View Website</a>
      <a href="logout.php">Logout</a>
    </div>
  </aside>

  <!-- Main Content -->
  <main class="main-content">
    <div class="page-header">
      <h1><?php echo [
        'dashboard' => 'Dashboard',
        'logo' => 'Site Logos',
        'hero' => 'Hero Background',
        'settings' => 'Content Settings',
        'contact_icons' => 'Contact Icons',
        'services' => 'Services',
        'projects' => 'Projects',
        'why' => 'Why Us',
        'messages' => 'Messages',
        'password' => 'Change Password'
      ][$tab] ?? 'Dashboard'; ?></h1>
      <div class="user-info">Logged in as <strong><?php echo sanitize($_SESSION['admin_username']); ?></strong></div>
    </div>

    <?php if ($message): ?>
    <div class="alert alert-<?php echo $messageType; ?>"><?php echo sanitize($message); ?></div>
    <?php endif; ?>

    <!-- Dashboard Tab -->
    <?php if ($tab == 'dashboard'): ?>
    <div class="stats-grid">
      <div class="stat-card"><div class="stat-value"><?php echo $totalProjects; ?></div><div class="stat-label">Projects</div></div>
      <div class="stat-card"><div class="stat-value"><?php echo $totalServices; ?></div><div class="stat-label">Services</div></div>
      <div class="stat-card"><div class="stat-value"><?php echo $totalMessages; ?></div><div class="stat-label">Messages (<?php echo $unreadMessages; ?> unread)</div></div>
      <div class="stat-card"><div class="stat-value">2</div><div class="stat-label">Languages</div></div>
    </div>

    <div class="card">
      <div class="card-header"><h3>Recent Messages</h3><a href="?tab=messages" style="color:#00e5a0;text-decoration:none;font-size:0.8rem;">View All →</a></div>
      <table>
        <thead><tr><th>Status</th><th>Name</th><th>Email</th><th>Date</th></tr></thead>
        <tbody>
          <?php $recentMessages = array_slice($allMessages, 0, 5);
          if (empty($recentMessages)): ?>
          <tr><td colspan="4" style="text-align:center;color:#88889a;padding:2rem;">No messages</td></tr>
          <?php else: foreach ($recentMessages as $msg): ?>
          <tr>
            <td><span class="status-dot <?php echo $msg['is_read'] ? 'read' : 'unread'; ?>"></span><?php echo $msg['is_read'] ? 'Read' : 'New'; ?></td>
            <td><?php echo sanitize($msg['first_name'] . ' ' . $msg['last_name']); ?></td>
            <td><?php echo sanitize($msg['email']); ?></td>
            <td><?php echo date('d M Y', strtotime($msg['created_at'])); ?></td>
          </tr>
          <?php endforeach; endif; ?>
        </tbody>
    </table>
    </div>

    <!-- Logos Tab with Size Control -->
    <?php elseif ($tab == 'logo'): ?>
    <div class="card">
      <div class="card-header"><h3>Site Logo (Header)</h3></div>
      <div class="card-body">
        <?php if (!empty($siteLogo) && file_exists($siteLogo)): ?>
        <img src="<?php echo $siteLogo; ?>" class="logo-preview" style="height:<?php echo $logoSize; ?>px; width:auto;">
        <div class="size-slider">
          <span style="font-size:0.7rem;">Size:</span>
          <input type="range" min="20" max="80" value="<?php echo $logoSize; ?>" id="logoSizeSlider" step="1">
          <span class="size-value" id="logoSizeValue"><?php echo $logoSize; ?>px</span>
          <form method="POST" id="logoSizeForm" style="display:inline;">
            <input type="hidden" name="action" value="update_logo_size">
            <input type="hidden" name="logo_size" id="logoSizeInput" value="<?php echo $logoSize; ?>">
            <button type="submit" class="btn btn-primary btn-sm">Save Size</button>
          </form>
        </div>
        <form method="POST" style="margin-top:1rem;" onsubmit="return confirm('Remove logo?')">
          <input type="hidden" name="action" value="remove_logo">
          <button type="submit" class="btn btn-danger btn-sm">Remove Logo</button>
        </form>
        <?php endif; ?>
        <form method="POST" enctype="multipart/form-data" style="margin-top:1rem;">
          <input type="hidden" name="action" value="upload_logo">
          <div class="form-group">
            <label>Upload New Logo</label>
            <div class="file-upload" onclick="document.getElementById('logoFile').click()">
              Click to upload image<br><small style="color:#88889a;">PNG, JPG, SVG, WebP - Max 5MB</small>
            </div>
            <input type="file" id="logoFile" name="logo" accept="image/*" style="display:none;" onchange="previewFile(this,'logoPreview')">
            <img id="logoPreview" class="img-preview" style="display:none;">
          </div>
          <button type="submit" class="btn btn-primary">Upload Logo</button>
        </form>
      </div>
    </div>

    <div class="card">
      <div class="card-header"><h3>Footer Logo</h3></div>
      <div class="card-body">
        <?php if (!empty($footerLogo) && file_exists($footerLogo)): ?>
        <img src="<?php echo $footerLogo; ?>" class="logo-preview" style="height:<?php echo $footerLogoSize; ?>px; width:auto;">
        <div class="size-slider">
          <span style="font-size:0.7rem;">Size:</span>
          <input type="range" min="20" max="60" value="<?php echo $footerLogoSize; ?>" id="footerLogoSizeSlider" step="1">
          <span class="size-value" id="footerLogoSizeValue"><?php echo $footerLogoSize; ?>px</span>
          <form method="POST" id="footerLogoSizeForm" style="display:inline;">
            <input type="hidden" name="action" value="update_footer_logo_size">
            <input type="hidden" name="footer_logo_size" id="footerLogoSizeInput" value="<?php echo $footerLogoSize; ?>">
            <button type="submit" class="btn btn-primary btn-sm">Save Size</button>
          </form>
        </div>
        <form method="POST" style="margin-top:1rem;" onsubmit="return confirm('Remove footer logo?')">
          <input type="hidden" name="action" value="remove_footer_logo">
          <button type="submit" class="btn btn-danger btn-sm">Remove Footer Logo</button>
        </form>
        <?php endif; ?>
        <form method="POST" enctype="multipart/form-data" style="margin-top:1rem;">
          <input type="hidden" name="action" value="upload_footer_logo">
          <div class="form-group">
            <label>Upload Footer Logo</label>
            <div class="file-upload" onclick="document.getElementById('footerLogoFile').click()">
              Click to upload image<br><small style="color:#88889a;">PNG, JPG, SVG, WebP - Max 5MB</small>
            </div>
            <input type="file" id="footerLogoFile" name="footer_logo" accept="image/*" style="display:none;" onchange="previewFile(this,'footerLogoPreview')">
            <img id="footerLogoPreview" class="img-preview" style="display:none;">
          </div>
          <button type="submit" class="btn btn-primary">Upload Footer Logo</button>
        </form>
      </div>
    </div>

    <!-- Hero Background Tab -->
    <?php elseif ($tab == 'hero'): ?>
    <div class="card">
      <div class="card-header"><h3>Hero Section Background</h3></div>
      <div class="card-body">
        <p style="margin-bottom:1rem;font-size:0.85rem;color:#a0a0b5;">Upload an image to use as background behind the hero section.</p>
        
        <?php if (!empty($heroBg) && file_exists($heroBg)): ?>
        <img src="<?php echo $heroBg; ?>" style="max-width:100%;max-height:200px;border-radius:8px;margin-bottom:1rem;border:1px solid #2a2a35;">
        <form method="POST" style="margin-bottom:1rem;" onsubmit="return confirm('Remove background?')">
          <input type="hidden" name="action" value="remove_hero_bg">
          <button type="submit" class="btn btn-danger btn-sm">Remove Background</button>
        </form>
        <?php endif; ?>
        
        <form method="POST" enctype="multipart/form-data">
          <input type="hidden" name="action" value="upload_hero_bg">
          <div class="form-group">
            <label>Upload Background Image</label>
            <div class="file-upload" onclick="document.getElementById('heroBgFile').click()">
              Click to upload background image<br><small style="color:#88889a;">Recommended: 1920x1080px or larger</small>
            </div>
            <input type="file" id="heroBgFile" name="hero_bg" accept="image/*" style="display:none;" onchange="previewFile(this,'heroBgPreview')">
            <img id="heroBgPreview" class="img-preview" style="display:none;">
          </div>
          <button type="submit" class="btn btn-primary">Upload Background</button>
        </form>
      </div>
    </div>

    <!-- Settings Tab -->
    <?php elseif ($tab == 'settings'): ?>
    <?php $slang = $_GET['slang'] ?? 'en'; $s = $slang == 'en' ? $settingsEN : $settingsIT; ?>
    <div style="display:flex;gap:0.5rem;margin-bottom:1rem;">
      <a href="?tab=settings&slang=en" class="btn <?php echo $slang=='en'?'btn-primary':'btn-secondary'; ?> btn-sm">English</a>
      <a href="?tab=settings&slang=it" class="btn <?php echo $slang=='it'?'btn-primary':'btn-secondary'; ?> btn-sm">Italian</a>
    </div>
    <div class="card">
      <div class="card-header"><h3>Homepage Content (<?php echo strtoupper($slang); ?>)</h3></div>
      <div class="card-body">
        <form method="POST">
          <input type="hidden" name="action" value="update_settings">
          <input type="hidden" name="lang" value="<?php echo $slang; ?>">
          
          <h4 style="margin:1rem 0 0.5rem;font-size:0.85rem;color:#a0a0b5;">Hero Section</h4>
          <div class="form-row">
            <div class="form-group"><label>Site Title</label><input type="text" name="site_title" value="<?php echo sanitize($s['site_title'] ?? ''); ?>"></div>
            <div class="form-group"><label>Hero Eyebrow</label><input type="text" name="hero_eyebrow" value="<?php echo sanitize($s['hero_eyebrow'] ?? ''); ?>"></div>
          </div>
          <div class="form-row">
            <div class="form-group"><label>Hero Line 1</label><input type="text" name="hero_title_line1" value="<?php echo sanitize($s['hero_title_line1'] ?? ''); ?>"></div>
            <div class="form-group"><label>Hero Line 2</label><input type="text" name="hero_title_line2" value="<?php echo sanitize($s['hero_title_line2'] ?? ''); ?>"></div>
          </div>
          <div class="form-group"><label>Hero Subtitle</label><textarea name="hero_subtitle"><?php echo sanitize($s['hero_subtitle'] ?? ''); ?></textarea></div>
          <div class="form-row">
            <div class="form-group"><label>CTA Primary</label><input type="text" name="hero_cta_primary" value="<?php echo sanitize($s['hero_cta_primary'] ?? ''); ?>"></div>
            <div class="form-group"><label>CTA Secondary</label><input type="text" name="hero_cta_secondary" value="<?php echo sanitize($s['hero_cta_secondary'] ?? ''); ?>"></div>
          </div>
          
          <h4 style="margin:1rem 0 0.5rem;font-size:0.85rem;color:#a0a0b5;">Statistics</h4>
          <div class="form-row">
            <div class="form-group"><label>Stat 1</label><input type="text" name="stat1_num" value="<?php echo sanitize($s['stat1_num'] ?? ''); ?>"></div>
            <div class="form-group"><label>Stat 1 Label</label><input type="text" name="stat1_label" value="<?php echo sanitize($s['stat1_label'] ?? ''); ?>"></div>
          </div>
          <div class="form-row">
            <div class="form-group"><label>Stat 2</label><input type="text" name="stat2_num" value="<?php echo sanitize($s['stat2_num'] ?? ''); ?>"></div>
            <div class="form-group"><label>Stat 2 Label</label><input type="text" name="stat2_label" value="<?php echo sanitize($s['stat2_label'] ?? ''); ?>"></div>
          </div>
          <div class="form-row">
            <div class="form-group"><label>Stat 3</label><input type="text" name="stat3_num" value="<?php echo sanitize($s['stat3_num'] ?? ''); ?>"></div>
            <div class="form-group"><label>Stat 3 Label</label><input type="text" name="stat3_label" value="<?php echo sanitize($s['stat3_label'] ?? ''); ?>"></div>
          </div>
          <div class="form-row">
            <div class="form-group"><label>Stat 4</label><input type="text" name="stat4_num" value="<?php echo sanitize($s['stat4_num'] ?? ''); ?>"></div>
            <div class="form-group"><label>Stat 4 Label</label><input type="text" name="stat4_label" value="<?php echo sanitize($s['stat4_label'] ?? ''); ?>"></div>
          </div>
          
          <h4 style="margin:1rem 0 0.5rem;font-size:0.85rem;color:#a0a0b5;">Section Texts</h4>
          <div class="form-group"><label>Services Label</label><input type="text" name="services_section_label" value="<?php echo sanitize($s['services_section_label'] ?? ''); ?>"></div>
          <div class="form-group"><label>Services Title</label><input type="text" name="services_title" value="<?php echo sanitize($s['services_title'] ?? ''); ?>"></div>
          <div class="form-group"><label>Services Description</label><textarea name="services_desc"><?php echo sanitize($s['services_desc'] ?? ''); ?></textarea></div>
          
          <div class="form-group"><label>Portfolio Label</label><input type="text" name="portfolio_section_label" value="<?php echo sanitize($s['portfolio_section_label'] ?? ''); ?>"></div>
          <div class="form-group"><label>Portfolio Title</label><input type="text" name="portfolio_title" value="<?php echo sanitize($s['portfolio_title'] ?? ''); ?>"></div>
          <div class="form-group"><label>Portfolio Description</label><textarea name="portfolio_desc"><?php echo sanitize($s['portfolio_desc'] ?? ''); ?></textarea></div>
          
          <div class="form-group"><label>Why Us Label</label><input type="text" name="why_section_label" value="<?php echo sanitize($s['why_section_label'] ?? ''); ?>"></div>
          <div class="form-group"><label>Why Us Title</label><input type="text" name="why_title" value="<?php echo sanitize($s['why_title'] ?? ''); ?>"></div>
          <div class="form-group"><label>Why Us Description</label><textarea name="why_desc"><?php echo sanitize($s['why_desc'] ?? ''); ?></textarea></div>
          
          <div class="form-group"><label>Contact Label</label><input type="text" name="contact_section_label" value="<?php echo sanitize($s['contact_section_label'] ?? ''); ?>"></div>
          <div class="form-group"><label>Contact Title</label><input type="text" name="contact_title" value="<?php echo sanitize($s['contact_title'] ?? ''); ?>"></div>
          <div class="form-group"><label>Contact Description</label><textarea name="contact_desc"><?php echo sanitize($s['contact_desc'] ?? ''); ?></textarea></div>
          
          <h4 style="margin:1rem 0 0.5rem;font-size:0.85rem;color:#a0a0b5;">Contact Info & Footer</h4>
          <div class="form-row">
            <div class="form-group"><label>Contact Email</label><input type="text" name="contact_email" value="<?php echo sanitize($s['contact_email'] ?? ''); ?>"></div>
            <div class="form-group"><label>Contact Phone</label><input type="text" name="contact_phone" value="<?php echo sanitize($s['contact_phone'] ?? ''); ?>"></div>
          </div>
          <div class="form-row">
            <div class="form-group"><label>Location</label><input type="text" name="contact_location" value="<?php echo sanitize($s['contact_location'] ?? ''); ?>"></div>
            <div class="form-group"><label>Support Text</label><input type="text" name="contact_support" value="<?php echo sanitize($s['contact_support'] ?? ''); ?>"></div>
          </div>
          <div class="form-group"><label>Footer Copyright</label><input type="text" name="footer_copyright" value="<?php echo sanitize($s['footer_copyright'] ?? ''); ?>"></div>
          
          <button type="submit" class="btn btn-primary">Save Settings</button>
        </form>
      </div>
    </div>

    <!-- Contact Icons Tab -->
    <?php elseif ($tab == 'contact_icons'): ?>
    <div class="card">
      <div class="card-header"><h3>Contact Section Icons</h3></div>
      <div class="card-body">
        <form method="POST" enctype="multipart/form-data">
          <input type="hidden" name="action" value="update_contact_icons">
          
          <div class="form-row">
            <div class="form-group">
              <label>Email Icon</label>
              <input type="text" name="email_icon" value="<?php echo sanitize($contactIcons['email_icon'] ?? ''); ?>" placeholder="📧 or text/emoji">
              <div class="file-upload" style="margin-top:0.5rem;padding:0.5rem;" onclick="document.getElementById('emailIconFile').click()">Upload Image</div>
              <input type="file" id="emailIconFile" name="email_icon_file" accept="image/*" style="display:none;" onchange="previewFile(this,'emailIconPreview')">
              <img id="emailIconPreview" class="img-preview" style="display:none;">
            </div>
            <div class="form-group">
              <label>Phone Icon</label>
              <input type="text" name="phone_icon" value="<?php echo sanitize($contactIcons['phone_icon'] ?? ''); ?>" placeholder="📞 or text/emoji">
              <div class="file-upload" style="margin-top:0.5rem;padding:0.5rem;" onclick="document.getElementById('phoneIconFile').click()">Upload Image</div>
              <input type="file" id="phoneIconFile" name="phone_icon_file" accept="image/*" style="display:none;" onchange="previewFile(this,'phoneIconPreview')">
              <img id="phoneIconPreview" class="img-preview" style="display:none;">
            </div>
          </div>
          
          <div class="form-row">
            <div class="form-group">
              <label>Location Icon</label>
              <input type="text" name="location_icon" value="<?php echo sanitize($contactIcons['location_icon'] ?? ''); ?>" placeholder="📍 or text/emoji">
              <div class="file-upload" style="margin-top:0.5rem;padding:0.5rem;" onclick="document.getElementById('locationIconFile').click()">Upload Image</div>
              <input type="file" id="locationIconFile" name="location_icon_file" accept="image/*" style="display:none;" onchange="previewFile(this,'locationIconPreview')">
              <img id="locationIconPreview" class="img-preview" style="display:none;">
            </div>
            <div class="form-group">
              <label>Support Icon</label>
              <input type="text" name="support_icon" value="<?php echo sanitize($contactIcons['support_icon'] ?? ''); ?>" placeholder="🕐 or text/emoji">
              <div class="file-upload" style="margin-top:0.5rem;padding:0.5rem;" onclick="document.getElementById('supportIconFile').click()">Upload Image</div>
              <input type="file" id="supportIconFile" name="support_icon_file" accept="image/*" style="display:none;" onchange="previewFile(this,'supportIconPreview')">
              <img id="supportIconPreview" class="img-preview" style="display:none;">
            </div>
          </div>
          
          <button type="submit" class="btn btn-primary">Save Icons</button>
        </form>
      </div>
    </div>

    <!-- Services Tab -->
    <?php elseif ($tab == 'services'): ?>
    <div class="card">
      <div class="card-header"><h3>Services (<?php echo count($allServices); ?>)</h3>
        <button class="btn btn-primary btn-sm" onclick="openModal('addServiceModal')">+ Add Service</button>
      </div>
      <table>
        <thead><tr><th>Image</th><th>Title (EN)</th><th>Title (IT)</th><th>Tags</th><th>Active</th><th>Actions</th></tr></thead>
        <tbody>
          <?php foreach ($allServices as $svc): ?>
          <tr>
            <td>
              <?php if (!empty($svc['image']) && file_exists($svc['image'])): ?>
              <img src="<?php echo $svc['image']; ?>" class="img-thumb" alt="">
              <?php else: ?>
              <span style="font-size:1.2rem;"><?php echo sanitize($svc['icon']); ?></span>
              <?php endif; ?>
            </td>
            <td><?php echo sanitize($svc['title_en']); ?></td>
            <td><?php echo sanitize($svc['title_it']); ?></td>
            <td><?php echo sanitize($svc['tags']); ?></td>
            <td><?php echo $svc['is_active'] ? 'Yes' : 'No'; ?></td>
            <td>
              <button class="btn btn-primary btn-sm" onclick='editService(<?php echo json_encode($svc); ?>)'>Edit</button>
              <form method="POST" style="display:inline;" onsubmit="return confirm('Delete?')">
                <input type="hidden" name="action" value="delete_service"><input type="hidden" name="id" value="<?php echo $svc['id']; ?>">
                <button class="btn btn-danger btn-sm">Delete</button>
              </form>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
    </table>
    </div>

    <!-- Add Service Modal -->
    <div class="modal-overlay" id="addServiceModal"><div class="modal">
      <h3>Add New Service</h3>
      <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="action" value="add_service">
        <div class="form-row">
          <div class="form-group"><label>Icon</label><input type="text" name="icon" value="🚀"></div>
          <div class="form-group"><label>Sort Order</label><input type="number" name="sort_order" value="0"></div>
        </div>
        <div class="form-group">
          <label>Image</label>
          <div class="file-upload" onclick="document.getElementById('svcImage').click()">Click to upload</div>
          <input type="file" id="svcImage" name="service_image" accept="image/*" style="display:none;" onchange="previewFile(this,'svcPreview')">
          <img id="svcPreview" class="img-preview" style="display:none;">
        </div>
        <div class="form-row">
          <div class="form-group"><label>Title (EN)</label><input type="text" name="title_en" required></div>
          <div class="form-group"><label>Title (IT)</label><input type="text" name="title_it" required></div>
        </div>
        <div class="form-group"><label>Description (EN)</label><textarea name="description_en" required></textarea></div>
        <div class="form-group"><label>Description (IT)</label><textarea name="description_it" required></textarea></div>
        <div class="form-group"><label>Tags (comma)</label><input type="text" name="tags"></div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" onclick="closeModal('addServiceModal')">Cancel</button>
          <button type="submit" class="btn btn-primary">Add</button>
        </div>
      </form>
    </div></div>

    <!-- Edit Service Modal -->
    <div class="modal-overlay" id="editServiceModal"><div class="modal">
      <h3>Edit Service</h3>
      <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="action" value="update_service">
        <input type="hidden" name="id" id="es_id">
        <input type="hidden" name="existing_image" id="es_existing_image">
        <div class="form-row">
          <div class="form-group"><label>Icon</label><input type="text" name="icon" id="es_icon"></div>
          <div class="form-group"><label>Sort Order</label><input type="number" name="sort_order" id="es_sort"></div>
        </div>
        <div class="form-group">
          <label>Image</label>
          <div id="es_current_img" style="margin-bottom:0.5rem;"></div>
          <div class="file-upload" onclick="document.getElementById('esImage').click()">Click to change</div>
          <input type="file" id="esImage" name="service_image" accept="image/*" style="display:none;" onchange="previewFile(this,'esPreview')">
          <img id="esPreview" class="img-preview" style="display:none;">
        </div>
        <div class="form-row">
          <div class="form-group"><label>Title (EN)</label><input type="text" name="title_en" id="es_title_en"></div>
          <div class="form-group"><label>Title (IT)</label><input type="text" name="title_it" id="es_title_it"></div>
        </div>
        <div class="form-group"><label>Description (EN)</label><textarea name="description_en" id="es_desc_en"></textarea></div>
        <div class="form-group"><label>Description (IT)</label><textarea name="description_it" id="es_desc_it"></textarea></div>
        <div class="form-group"><label>Tags</label><input type="text" name="tags" id="es_tags"></div>
        <div class="form-group"><label>Active</label><select name="is_active" id="es_active"><option value="1">Yes</option><option value="0">No</option></select></div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" onclick="closeModal('editServiceModal')">Cancel</button>
          <button type="submit" class="btn btn-primary">Update</button>
        </div>
      </form>
    </div></div>

    <!-- Projects Tab -->
    <?php elseif ($tab == 'projects'): ?>
    <div class="card">
      <div class="card-header"><h3>Projects (<?php echo count($allProjects); ?>)</h3>
        <button class="btn btn-primary btn-sm" onclick="openModal('addProjectModal')">+ Add Project</button>
      </div>
      <table>
        <thead><tr><th>Image</th><th>Title (EN)</th><th>Category</th><th>Active</th><th>Actions</th></tr></thead>
        <tbody>
          <?php foreach ($allProjects as $proj): ?>
          <tr>
            <td>
              <?php if (!empty($proj['image']) && file_exists($proj['image'])): ?>
              <img src="<?php echo $proj['image']; ?>" class="img-thumb" alt="">
              <?php else: ?>
              <span style="font-size:1.2rem;"><?php echo sanitize($proj['icon']); ?></span>
              <?php endif; ?>
            </td>
            <td><?php echo sanitize($proj['title_en']); ?></td>
            <td><?php echo sanitize($proj['category_en']); ?></td>
            <td><?php echo $proj['is_active'] ? 'Yes' : 'No'; ?></td>
            <td>
              <button class="btn btn-primary btn-sm" onclick='editProject(<?php echo json_encode($proj); ?>)'>Edit</button>
              <form method="POST" style="display:inline;" onsubmit="return confirm('Delete?')">
                <input type="hidden" name="action" value="delete_project"><input type="hidden" name="id" value="<?php echo $proj['id']; ?>">
                <button class="btn btn-danger btn-sm">Delete</button>
              </form>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
    </table>
    </div>

    <!-- Add Project Modal -->
    <div class="modal-overlay" id="addProjectModal"><div class="modal">
      <h3>Add New Project</h3>
      <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="action" value="add_project">
        <div class="form-row">
          <div class="form-group"><label>Icon</label><input type="text" name="icon" value="🏢"></div>
          <div class="form-group"><label>Bg Class</label><select name="bg_class"><?php foreach($bgClasses as $bg): ?><option value="<?php echo $bg; ?>"><?php echo $bg; ?></option><?php endforeach; ?></select></div>
        </div>
        <div class="form-group">
          <label>Image</label>
          <div class="file-upload" onclick="document.getElementById('projImage').click()">Click to upload</div>
          <input type="file" id="projImage" name="project_image" accept="image/*" style="display:none;" onchange="previewFile(this,'projPreview')">
          <img id="projPreview" class="img-preview" style="display:none;">
        </div>
        <div class="form-row">
          <div class="form-group"><label>Category (EN)</label><input type="text" name="category_en" required></div>
          <div class="form-group"><label>Category (IT)</label><input type="text" name="category_it" required></div>
        </div>
        <div class="form-row">
          <div class="form-group"><label>Title (EN)</label><input type="text" name="title_en" required></div>
          <div class="form-group"><label>Title (IT)</label><input type="text" name="title_it" required></div>
        </div>
        <div class="form-group"><label>Description (EN)</label><textarea name="description_en" required></textarea></div>
        <div class="form-group"><label>Description (IT)</label><textarea name="description_it" required></textarea></div>
        <div class="form-group"><label>Sort Order</label><input type="number" name="sort_order" value="0"></div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" onclick="closeModal('addProjectModal')">Cancel</button>
          <button type="submit" class="btn btn-primary">Add</button>
        </div>
      </form>
    </div></div>

    <!-- Edit Project Modal -->
    <div class="modal-overlay" id="editProjectModal"><div class="modal">
      <h3>Edit Project</h3>
      <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="action" value="update_project">
        <input type="hidden" name="id" id="ep_id">
        <input type="hidden" name="existing_image" id="ep_existing_image">
        <div class="form-row">
          <div class="form-group"><label>Icon</label><input type="text" name="icon" id="ep_icon"></div>
          <div class="form-group"><label>Bg Class</label><select name="bg_class" id="ep_bg"><?php foreach($bgClasses as $bg): ?><option value="<?php echo $bg; ?>"><?php echo $bg; ?></option><?php endforeach; ?></select></div>
        </div>
        <div class="form-group">
          <label>Image</label>
          <div id="ep_current_img" style="margin-bottom:0.5rem;"></div>
          <div class="file-upload" onclick="document.getElementById('epImage').click()">Click to change</div>
          <input type="file" id="epImage" name="project_image" accept="image/*" style="display:none;" onchange="previewFile(this,'epPreview')">
          <img id="epPreview" class="img-preview" style="display:none;">
        </div>
        <div class="form-row">
          <div class="form-group"><label>Category (EN)</label><input type="text" name="category_en" id="ep_cat_en"></div>
          <div class="form-group"><label>Category (IT)</label><input type="text" name="category_it" id="ep_cat_it"></div>
        </div>
        <div class="form-row">
          <div class="form-group"><label>Title (EN)</label><input type="text" name="title_en" id="ep_title_en"></div>
          <div class="form-group"><label>Title (IT)</label><input type="text" name="title_it" id="ep_title_it"></div>
        </div>
        <div class="form-group"><label>Description (EN)</label><textarea name="description_en" id="ep_desc_en"></textarea></div>
        <div class="form-group"><label>Description (IT)</label><textarea name="description_it" id="ep_desc_it"></textarea></div>
        <div class="form-row">
          <div class="form-group"><label>Sort Order</label><input type="number" name="sort_order" id="ep_sort"></div>
          <div class="form-group"><label>Active</label><select name="is_active" id="ep_active"><option value="1">Yes</option><option value="0">No</option></select></div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" onclick="closeModal('editProjectModal')">Cancel</button>
          <button type="submit" class="btn btn-primary">Update</button>
        </div>
      </form>
    </div></div>

    <!-- Why Us Tab -->
    <?php elseif ($tab == 'why'): ?>
    <div class="card">
      <div class="card-header"><h3>Why Us Items</h3></div>
      <div class="card-body">
        <?php foreach ($allWhyItems as $item): ?>
        <form method="POST" enctype="multipart/form-data" style="margin-bottom:1.5rem;padding:1rem;background:#14141c;border-radius:8px;border:1px solid #2a2a35;">
          <input type="hidden" name="action" value="update_why">
          <input type="hidden" name="id" value="<?php echo $item['id']; ?>">
          <input type="hidden" name="existing_image" id="why_existing_<?php echo $item['id']; ?>" value="<?php echo $item['image']; ?>">
          
          <?php if (!empty($item['image']) && file_exists($item['image'])): ?>
          <div style="margin-bottom:0.5rem;">
            <img src="<?php echo $item['image']; ?>" style="height:50px;border-radius:8px;">
          </div>
          <?php endif; ?>
          
          <div class="form-row">
            <div class="form-group"><label>Icon/Emoji</label><input type="text" name="icon" value="<?php echo sanitize($item['icon']); ?>"></div>
            <div class="form-group"><label>Sort Order</label><input type="number" name="sort_order" value="<?php echo $item['sort_order']; ?>"></div>
          </div>
          <div class="form-group">
            <label>Image (optional)</label>
            <div class="file-upload" onclick="document.getElementById('whyImage_<?php echo $item['id']; ?>').click()">Click to upload image</div>
            <input type="file" id="whyImage_<?php echo $item['id']; ?>" name="why_image" accept="image/*" style="display:none;" onchange="previewFile(this,'whyPreview_<?php echo $item['id']; ?>')">
            <img id="whyPreview_<?php echo $item['id']; ?>" class="img-preview" style="display:none;">
          </div>
          <div class="form-row">
            <div class="form-group"><label>Title (EN)</label><input type="text" name="title_en" value="<?php echo sanitize($item['title_en']); ?>" required></div>
            <div class="form-group"><label>Title (IT)</label><input type="text" name="title_it" value="<?php echo sanitize($item['title_it']); ?>" required></div>
          </div>
          <div class="form-row">
            <div class="form-group"><label>Description (EN)</label><textarea name="description_en"><?php echo sanitize($item['description_en']); ?></textarea></div>
            <div class="form-group"><label>Description (IT)</label><textarea name="description_it"><?php echo sanitize($item['description_it']); ?></textarea></div>
          </div>
          <div class="form-group"><label>Active</label><select name="is_active"><option value="1" <?php echo $item['is_active']?'selected':''; ?>>Yes</option><option value="0" <?php echo !$item['is_active']?'selected':''; ?>>No</option></select></div>
          <button type="submit" class="btn btn-primary btn-sm">Update</button>
        </form>
        <?php endforeach; ?>
      </div>
    </div>

    <!-- Messages Tab -->
    <?php elseif ($tab == 'messages'): ?>
    <div class="card">
      <div class="card-header"><h3>Messages (<?php echo count($allMessages); ?>)</h3></div>
      <?php if (empty($allMessages)): ?>
      <div class="card-body" style="text-align:center;color:#88889a;padding:2rem;">No messages</div>
      <?php else: ?>
      <table>
        <thead><tr><th>Status</th><th>Name</th><th>Email</th><th>Date</th><th>Actions</th></tr></thead>
        <tbody>
          <?php foreach ($allMessages as $msg): ?>
          <tr>
            <td><span class="status-dot <?php echo $msg['is_read']?'read':'unread'; ?>"></span><?php echo $msg['is_read']?'Read':'New'; ?></td>
            <td><?php echo sanitize($msg['first_name'].' '.$msg['last_name']); ?></td>
            <td><?php echo sanitize($msg['email']); ?></td>
            <td><?php echo date('d M H:i', strtotime($msg['created_at'])); ?></td>
            <td>
              <?php if (!$msg['is_read']): ?>
              <form method="POST" style="display:inline;">
                <input type="hidden" name="action" value="mark_read"><input type="hidden" name="id" value="<?php echo $msg['id']; ?>">
                <button class="btn btn-primary btn-sm">Mark Read</button>
              </form>
              <?php endif; ?>
              <button class="btn btn-secondary btn-sm" onclick='viewMessage(<?php echo json_encode($msg); ?>)'>View</button>
              <form method="POST" style="display:inline;" onsubmit="return confirm('Delete?')">
                <input type="hidden" name="action" value="delete_message"><input type="hidden" name="id" value="<?php echo $msg['id']; ?>">
                <button class="btn btn-danger btn-sm">Delete</button>
              </form>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
      <?php endif; ?>
    </div>

    <!-- View Message Modal -->
    <div class="modal-overlay" id="viewMessageModal"><div class="modal">
      <h3>Message Details</h3>
      <div id="messageContent"></div>
      <div class="modal-footer"><button type="button" class="btn btn-secondary" onclick="closeModal('viewMessageModal')">Close</button></div>
    </div></div>

    <!-- Password Tab -->
    <?php elseif ($tab == 'password'): ?>
    <div class="card">
      <div class="card-header"><h3>Change Password</h3></div>
      <div class="card-body">
        <form method="POST" style="max-width:400px;">
          <input type="hidden" name="action" value="change_password">
          <div class="form-group"><label>Current Password</label><input type="password" name="current_password" required></div>
          <div class="form-group"><label>New Password</label><input type="password" name="new_password" required minlength="6"></div>
          <div class="form-group"><label>Confirm Password</label><input type="password" name="confirm_password" required minlength="6"></div>
          <button type="submit" class="btn btn-primary">Change Password</button>
        </form>
      </div>
    </div>
    <?php endif; ?>
  </main>
</div>

<script>
  // Logo size slider
  const logoSlider = document.getElementById('logoSizeSlider');
  const logoValue = document.getElementById('logoSizeValue');
  const logoInput = document.getElementById('logoSizeInput');
  
  if (logoSlider) {
    logoSlider.addEventListener('input', function() {
      logoValue.textContent = this.value + 'px';
      logoInput.value = this.value;
    });
  }
  
  const footerSlider = document.getElementById('footerLogoSizeSlider');
  const footerValue = document.getElementById('footerLogoSizeValue');
  const footerInput = document.getElementById('footerLogoSizeInput');
  
  if (footerSlider) {
    footerSlider.addEventListener('input', function() {
      footerValue.textContent = this.value + 'px';
      footerInput.value = this.value;
    });
  }
  
  function openModal(id) { document.getElementById(id).classList.add('active'); }
  function closeModal(id) { document.getElementById(id).classList.remove('active'); }
  
  document.querySelectorAll('.modal-overlay').forEach(o => {
    o.addEventListener('click', function(e) { if (e.target === this) this.classList.remove('active'); });
  });
  
  function previewFile(input, previewId) {
    if (input.files && input.files[0]) {
      const reader = new FileReader();
      reader.onload = function(e) {
        const preview = document.getElementById(previewId);
        preview.src = e.target.result;
        preview.style.display = 'block';
      };
      reader.readAsDataURL(input.files[0]);
    }
  }
  
  function editService(data) {
    document.getElementById('es_id').value = data.id;
    document.getElementById('es_icon').value = data.icon;
    document.getElementById('es_title_en').value = data.title_en;
    document.getElementById('es_title_it').value = data.title_it;
    document.getElementById('es_desc_en').value = data.description_en;
    document.getElementById('es_desc_it').value = data.description_it;
    document.getElementById('es_tags').value = data.tags;
    document.getElementById('es_sort').value = data.sort_order;
    document.getElementById('es_active').value = data.is_active;
    document.getElementById('es_existing_image').value = data.image || '';
    document.getElementById('es_current_img').innerHTML = data.image ? '<img src="' + data.image + '" class="img-thumb"> <small>Current</small>' : '<small>No image</small>';
    document.getElementById('esPreview').style.display = 'none';
    openModal('editServiceModal');
  }
  
  function editProject(data) {
    document.getElementById('ep_id').value = data.id;
    document.getElementById('ep_icon').value = data.icon;
    document.getElementById('ep_bg').value = data.bg_class;
    document.getElementById('ep_cat_en').value = data.category_en;
    document.getElementById('ep_cat_it').value = data.category_it;
    document.getElementById('ep_title_en').value = data.title_en;
    document.getElementById('ep_title_it').value = data.title_it;
    document.getElementById('ep_desc_en').value = data.description_en;
    document.getElementById('ep_desc_it').value = data.description_it;
    document.getElementById('ep_sort').value = data.sort_order;
    document.getElementById('ep_active').value = data.is_active;
    document.getElementById('ep_existing_image').value = data.image || '';
    document.getElementById('ep_current_img').innerHTML = data.image ? '<img src="' + data.image + '" class="img-thumb"> <small>Current</small>' : '<small>No image</small>';
    document.getElementById('epPreview').style.display = 'none';
    openModal('editProjectModal');
  }
  
  function viewMessage(data) {
    document.getElementById('messageContent').innerHTML = `
      <p><strong>Name:</strong> ${data.first_name} ${data.last_name}</p>
      <p><strong>Email:</strong> ${data.email}</p>
      <p><strong>Company:</strong> ${data.company || '-'}</p>
      <p><strong>Service:</strong> ${data.service || '-'}</p>
      <p><strong>Date:</strong> ${data.created_at}</p>
      <hr style="margin:1rem 0;border-color:#2a2a35;">
      <p><strong>Message:</strong></p>
      <p style="white-space:pre-wrap;">${data.message}</p>
    `;
    openModal('viewMessageModal');
  }
</script>

</body>
</html>