<?php
// ✅ Start session before any output
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ✅ Check if admin is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: login.php");
    exit;
}

require_once 'db.php';


// ✅ Fetch branding settings
$stmt = $pdo->query("SELECT background_image, logo_image FROM branding WHERE id = 1");
$branding = $stmt->fetch();

// ✅ Define variables
$backgroundImage = $branding['background_image'] ?? '';
$logoImage = $branding['logo_image'] ?? '';


function convertToEmbedURL($url) {
    // YouTube: youtu.be or watch?v= → embed
    if (strpos($url, 'youtu.be/') !== false) {
        $video_id = basename(parse_url($url, PHP_URL_PATH));
        return 'https://www.youtube.com/embed/' . $video_id;
    }

    if (strpos($url, 'youtube.com/watch') !== false) {
        parse_str(parse_url($url, PHP_URL_QUERY), $params);
        if (!empty($params['v'])) {
            return 'https://www.youtube.com/embed/' . $params['v'];
        }
    }

    // Vimeo: standard or ?share=copy → player.vimeo.com
    if (strpos($url, 'vimeo.com/') !== false) {
        $parts = explode('/', parse_url($url, PHP_URL_PATH));
        $video_id = end($parts);
        return 'https://player.vimeo.com/video/' . $video_id;
    }

    // Return as-is if it doesn't match known formats
    return $url;
}



// ✅ Handle file uploads
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $uploadDir = "assets/images/";
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    $backgroundPath = null;
    $logoPath = null;

// ✅ Fetch existing branding data before upload
$stmt = $pdo->query("SELECT background_image, logo_image FROM branding WHERE id = 1");
$branding = $stmt->fetch();

// Handle Background Image Upload (Delete Old File First)
if (!empty($_FILES["background"]["name"])) {
    if (!empty($branding["background_image"]) && file_exists($branding["background_image"])) {
        unlink($branding["background_image"]); // ✅ Delete old file
    }
    
    $backgroundName = time() . "_bg_" . basename($_FILES["background"]["name"]);
    $backgroundPath = $uploadDir . $backgroundName;
    move_uploaded_file($_FILES["background"]["tmp_name"], $backgroundPath);
}


// ✅ Handle Logo Image Upload (Delete Old File First)
if (!empty($_FILES["logo"]["name"])) {
    if (!empty($branding["logo_image"]) && file_exists($branding["logo_image"])) {
        unlink($branding["logo_image"]);
    }

    $logoName = time() . "_logo_" . basename($_FILES["logo"]["name"]);
    $logoPath = $uploadDir . $logoName;
    move_uploaded_file($_FILES["logo"]["tmp_name"], $logoPath);
}

// ✅ Default to existing Open Graph image
$ogImagePath = $branding["open_graph_image"] ?? '';

// ✅ If a new image is uploaded
if (!empty($_FILES["open_graph_image"]["name"])) {
    $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/webp'];

    if (!in_array($_FILES["open_graph_image"]["type"], $allowedMimeTypes)) {
        die("❌ Invalid file type. Only JPG, PNG, or WEBP images are allowed.");
    }

    $cleanName = preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', $_FILES["open_graph_image"]["name"]);
    $ogImageName = time() . "_og_" . basename($cleanName);
    $newOgImagePath = $uploadDir . $ogImageName;

    // ✅ Delete old OG image if it exists
    if (!empty($ogImagePath) && file_exists($ogImagePath)) {
        unlink($ogImagePath);
    }

    move_uploaded_file($_FILES["open_graph_image"]["tmp_name"], $newOgImagePath);
    $ogImagePath = $newOgImagePath; // ✅ Only update if new one uploaded
}


    // ✅ Update branding table using PDO
// ✅ Safely preserve background and logo without touching Open Graph
$backgroundPath = !empty($_FILES["background"]["name"]) ? $backgroundPath : $branding["background_image"];
$logoPath = !empty($_FILES["logo"]["name"]) ? $logoPath : $branding["logo_image"];
$openai_api_key = trim($_POST['openai_api_key'] ?? '');

// ✅ Preserve open graph only if no new file is uploaded
if (empty($_FILES["open_graph_image"]["name"])) {
    $ogImagePath = $branding["open_graph_image"] ?? '';
}

// ✅ Preserve existing values if no new file is uploaded
$backgroundPath = !empty($_FILES["background"]["name"]) ? $backgroundPath : $branding["background_image"];
$logoPath = !empty($_FILES["logo"]["name"]) ? $logoPath : $branding["logo_image"];
$openai_api_key = trim($_POST['openai_api_key'] ?? '');

// ✅ Preserve footer_note only if field is present
$rawFooter = isset($_POST['footer_note']) ? $_POST['footer_note'] : null;
$cleanFooter = null;

if ($rawFooter !== null) {
    $cleanFooter = preg_replace('/\s*style\s*=\s*"[^"]*"/i', '', $rawFooter);
}


// ✅ Ensure open_graph_image always has a defined value before saving
if (empty($ogImagePath)) {
    $ogImagePath = $branding["open_graph_image"]; // Use existing image if no new one uploaded
}


// ✅ Base SQL
$sql = "UPDATE branding SET 
    brand_name = :brand,
    license_key = :license_key,
    background_image = :bg, 
    logo_image = :logo, 
    title = :title, 
    subtitle = :subtitle,
    bridge_video_url = :bridge_video_url,
    facebook_group_url = :facebook,
    default_leadsleap_id = :default_leadsleap_id,
    share_code_leads = :share_code_leads,
    share_code_referrals = :share_code_referrals,
    default_share_code = :default_share_code,
    theme_stylesheet = :theme_stylesheet,
    openai_api_key = :openai_api_key,
    footer_note = :footer_note";

// ✅ Only include open_graph_image if a new file was uploaded
if (!empty($_FILES["open_graph_image"]["name"])) {
    $sql .= ", open_graph_image = :og_image";
}

$sql .= " WHERE id = 1";

$stmt = $pdo->prepare($sql);

// ✅ Bind values
$params = [
    ':brand' => $_POST['brand_name'] ?? '',
    ':license_key' => $_POST['license_key'] ?? '',
    ':bg' => $backgroundPath,
    ':logo' => $logoPath,
    ':title' => $_POST['title'] ?? '',
    ':subtitle' => $_POST['subtitle'] ?? '',
    ':facebook' => $_POST['facebook_group_url'] ?? '',
    ':bridge_video_url' => convertToEmbedURL($_POST['bridge_video_url']),
    ':default_leadsleap_id' => $_POST['default_leadsleap_id'] ?? '',
    ':share_code_leads' => $_POST['share_code_leads'] ?? '',
    ':share_code_referrals' => $_POST['share_code_referrals'] ?? '',
    ':default_share_code' => $_POST['default_share_code'] ?? '',
    ':theme_stylesheet' => $_POST['theme_stylesheet'] ?? 'theme-orange.css',
    ':openai_api_key' => $openai_api_key
];

// ✅ Only bind footer_note if field was submitted
if ($cleanFooter !== null) {
    $params[':footer_note'] = $cleanFooter;
    $sql = str_replace('footer_note = :footer_note', 'footer_note = :footer_note', $sql); // keep it
} else {
    // Remove footer_note from SQL if it wasn’t submitted
    $sql = str_replace(', footer_note = :footer_note', '', $sql);
}


// ✅ Only bind open_graph_image if uploaded
if (!empty($_FILES["open_graph_image"]["name"])) {
    $params[':og_image'] = $ogImagePath;
}

$stmt->execute($params);







    echo "<script>alert('Branding updated successfully!'); window.location.href='admin-branding.php';</script>";
}

// ✅ Fetch existing branding settings
$stmt = $pdo->query("SELECT * FROM branding WHERE id = 1");
$branding = $stmt->fetch();

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Branding Settings</title>
<link rel="stylesheet" href="assets/css/styles.css">
<!-- Trumbowyg WYSIWYG Editor -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/ui/trumbowyg.min.css">
 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
body {
    font-family: Arial, sans-serif;
    text-align: center;
    background: #f8f9fa; /* Default background */
    <?php if (!empty($backgroundImage)): ?>
        background-image: url('<?= $backgroundImage; ?>');
        background-repeat: no-repeat;
        background-position: center center;
        background-attachment: fixed;
        background-size: cover;
    <?php endif; ?>
}

.container {
    margin: 0;
    width: 100%;
    background: white;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0px 4px 12px rgba(0,0,0,0.15);
}

table { 
    width: 100%; 
    border-collapse: collapse; 
    margin-top: 20px; 
}

th, td { 
    padding: 10px; 
    border: 1px solid #ddd; 
    text-align: left; 
}

th { 
    background: #007bff; 
    color: white; 
}

.edit-btn { 
    background: #28a745; 
    color: white; 
    padding: 5px 10px; 
    border: none; 
    cursor: pointer; 
    border-radius: 5px; 
}

.edit-btn:hover { 
    background: #218838; 
}

.footer {
    text-align: center;
    padding: 20px;
    font-size: 14px;
    color: white;
    background: rgba(0, 0, 0, 0.6); /* Semi-transparent */
    border-radius: 8px;
    width: 80%;
    margin: 40px auto 10px; /* Ensures spacing from other elements */
    position: relative;
    bottom: 0;
    clear: both; /* Forces it to clear any floating elements */
}

/* Force admin sidebar links to look right on dark background */
.admin-sidebar a {
  color: #fff !important;
  text-decoration: none;
}
.admin-sidebar a:hover {
  text-decoration: underline;
}

    </style>
    
</head>
<body style="display: flex; min-height: 100vh; margin: 0;">
<div class="admin-sidebar" style="width:220px; background:#343a40; padding:20px;">
  <?php include 'google-translate-widget-front-end.php'; ?>
  <?php include 'admin-links.php'; ?>
</div>

  <div style="flex-grow: 1; padding: 20px;">
<?php if (!empty($logoImage)): ?>
    <div style="text-align: center; padding: 20px;">
        <img src="<?= $logoImage; ?>" alt="Logo" style="max-width: 200px; height: auto;">
    </div>
<?php endif; ?>
    <div class="container">
        <a href="admin.php" class="admin-back">← Back to Admin Panel</a>
        <h2>Branding Settings</h2>

<form action="admin-branding.php" method="POST" enctype="multipart/form-data">

<label>License Key:</label>
<input type="text" name="license_key" value="<?= htmlspecialchars($branding['license_key'] ?? '') ?>" placeholder="Enter your license key">


    <label>Page Title:</label>
    <small class="text-muted">Used on the front end funnel bridge page.</small>
    <input type="text" name="title" value="<?= htmlspecialchars($branding['title'] ?? ''); ?>" placeholder="Enter main title">

    <label>Page Subtitle:</label>
    <small class="text-muted">Used on the front end funnel bridge page.</small>
    <input type="text" name="subtitle" value="<?= htmlspecialchars($branding['subtitle'] ?? ''); ?>" placeholder="Enter subtitle">
    
    <div class="mb-3">
    <label for="bridge_video_url" class="form-label">Bridge Page Video URL (YouTube or Vimeo – Any Format, Auto-Converted)</label>
    <small class="text-muted">Used on the front end funnel bridge page.</small>
    <input type="text" class="form-control" id="bridge_video_url" name="bridge_video_url" value="<?= htmlspecialchars($branding['bridge_video_url'] ?? '') ?>">
</div>
<div class="mb-3">
    <label for="open_graph_image" class="form-label">Open Graph Image URL</label>
    <small class="text-muted">This image will appear when users share your link on Facebook, X, etc. Recommended size: 1200x630px</small>
    <input type="file" name="open_graph_image" accept=".jpg,.jpeg,.png,.webp">
<?php if (!empty($branding['open_graph_image'])): ?>
    <div style="margin-top: 10px;">
        <img src="<?= $branding['open_graph_image']; ?>" style="max-width: 300px; border: 1px solid #ccc;">
    </div>
<?php endif; ?>
</div>

    
    <label>Brand Name (for emails, etc):</label>
    <small class="text-muted">Used as the sender name for system emails like "Forgot Password".</small>
<input type="text" name="brand_name" 
       value="<?= htmlspecialchars($branding['brand_name'] ?? '') ?>" 
       placeholder="e.g. MLM Lead Pro">


    
    <label>Facebook Group URL:</label>
    <small class="text-muted">Used inside the members login area at the top.</small>
<input type="url" name="facebook_group_url" value="<?= htmlspecialchars($branding['facebook_group_url'] ?? '') ?>" placeholder="https://www.facebook.com/groups/yourgroup">


    <label>Upload Background Image:</label>
    <small class="text-muted">Used on some system pages such as login page etc.</small>
    <input type="file" name="background">
    <?php if (!empty($branding["background_image"])) { ?>
        <img src="<?= $branding['background_image']; ?>" width="200px" style="display:block;margin-top:10px;">
    <?php } ?>

    <label>Upload Logo:</label>
    <small class="text-muted">Used on user login area and on some system pages such as login page etc.</small>
    <input type="file" name="logo">
    <?php if (!empty($branding["logo_image"])) { ?>
        <img src="<?= $branding['logo_image']; ?>" width="200px" style="display:block;margin-top:10px;">
    <?php } ?>
    
    
    <label>Select Color Theme:</label>
<small class="text-muted">Choose how your site looks — instantly updates all pages for your members.</small>

<div style="display: flex; gap: 20px; flex-wrap: wrap; justify-content: center; margin-bottom: 20px;">
  <?php
$themes = [
    ['file' => 'theme-orange.css', 'thumb' => 'theme-orange.png', 'label' => 'Orange'],
    ['file' => 'theme-green.css',  'thumb' => 'theme-green.png',  'label' => 'Green'],
    ['file' => 'theme-blue.css',   'thumb' => 'theme-blue.png',   'label' => 'Blue'],
    ['file' => 'theme-purple.css', 'thumb' => 'theme-purple.png', 'label' => 'Purple'],
    ['file' => 'theme-gold.css',   'thumb' => 'theme-gold.png',   'label' => 'Gold'],
    ['file' => 'theme-carbon.css', 'thumb' => 'theme-carbon.png', 'label' => 'Carbon'],
];
    foreach ($themes as $theme):
        $isSelected = ($branding['theme_stylesheet'] ?? 'theme-orange.css') === $theme['file'];
  ?>
    <label style="cursor: pointer; text-align: center;">
        <input type="radio" name="theme_stylesheet" value="<?= $theme['file'] ?>" <?= $isSelected ? 'checked' : '' ?> style="display: none;">
        <img src="assets/css/themes/<?= $theme['thumb'] ?>" alt="<?= $theme['label'] ?>" 
             style="border: 3px solid <?= $isSelected ? '#22c55e' : '#ccc' ?>; border-radius: 10px; width: 140px; height: auto; box-shadow: 0 2px 8px rgba(0,0,0,0.1); margin-bottom: 6px;">
        <div style="font-weight: bold; font-size: 14px; color: #444;"><?= $theme['label'] ?></div>
    </label>
  <?php endforeach; ?>
</div>

    
    
<label>Fallback LeadsLeap ID:</label>
<small class="text-muted">Used if sponsor hasn't saved a LeadsLeap ID.</small>
<input type="text" name="default_leadsleap_id" 
       value="<?= htmlspecialchars($branding['default_leadsleap_id'] ?? '') ?>" 
       placeholder="e.g. keyte or admin123">
       
       <label>Follow-Up Share Code (for Leads)</label>
<input type="text" name="share_code_leads" class="form-control" value="<?= htmlspecialchars($branding['share_code_leads'] ?? '') ?>">

<label>Follow-Up Share Code (for Referrals)</label>
<input type="text" name="share_code_referrals" class="form-control" value="<?= htmlspecialchars($branding['share_code_referrals'] ?? '') ?>">

       
       
       <label>Default Share Code for New Users:</label>
<small class="text-muted">Used to auto-clone a lead capture page on user registration.</small>
<input type="text" name="default_share_code" 
       value="<?= htmlspecialchars($branding['default_share_code'] ?? '') ?>" 
       placeholder="e.g. F6716D">



<div class="mb-3">
  <label for="openai_api_key" class="form-label">OpenAI API Key</label>
  <input type="text" class="form-control" id="openai_api_key" name="openai_api_key"
         value="<?= htmlspecialchars($branding['openai_api_key'] ?? '') ?>"
         placeholder="sk-..." autocomplete="off">
  <div class="form-text">Enter your OpenAI secret key to enable AI features.</div>
</div>


<label for="footer_note">Footer Note (Mini Editor)</label>
<small class="text-muted">Appears at the bottom of all pages. You can include a link or bold text.</small>
<textarea name="footer_note" id="footer_note" class="form-control"><?= htmlspecialchars($branding['footer_note'] ?? '') ?></textarea>
<small style="display:block; margin-top:5px; color:#777;">
💡 <strong>Tip:</strong> Avoid changing link colors — your selected theme will style links automatically.
</small>




    <button type="submit" class="save-btn">Save Branding</button>
</form>

    </div>
    
<?php include 'admin-footer.php'; ?>


</div> <!-- Close main-content -->
<script>
document.querySelectorAll('input[name="theme_stylesheet"]').forEach(radio => {
    radio.addEventListener('change', () => {
        document.querySelectorAll('input[name="theme_stylesheet"]').forEach(el => {
            el.nextElementSibling.style.border = '3px solid #ccc';
        });
        radio.nextElementSibling.style.border = '3px solid #22c55e';
    });
});
</script>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/trumbowyg.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/plugins/viewhtml/trumbowyg.viewhtml.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/plugins/link-target-button/trumbowyg.link-target-button.min.js"></script>


<script>
$(document).ready(function () {
  $('#footer_note').trumbowyg({
    btns: [
      ['bold', 'italic'],
      ['link', 'linkTarget'],
      ['viewHTML']
    ],
    autogrow: true,
    removeformatPasted: true
  });
});
</script>




</body>
</html>
