<?php include "header.php"; ?>
<?php
$user_id = $userdata['id'];
$uploadDir = realpath(__DIR__ . '/..') . '/uploads/logos/';
$uploadPublicPath = 'uploads/logos/';

// ---- 42 curated color templates (classic, premium/dark, vibrant, pastel) ----
$templates = [
    // ---- Classic / light ----
    'emerald'   => ['label' => 'Emerald (Default)', 'primary' => '#0F6B5C', 'secondary' => '#E8A33D', 'success' => '#1FAA59', 'bg' => '#EAF3F0', 'card' => '#FFFFFF', 'text' => '#0B1F1C'],
    'royal'     => ['label' => 'Royal Blue',         'primary' => '#1E3A8A', 'secondary' => '#3EA6FF', 'success' => '#22C55E', 'bg' => '#EAF1FB', 'card' => '#FFFFFF', 'text' => '#0B1730'],
    'sunset'    => ['label' => 'Sunset Orange',      'primary' => '#D35400', 'secondary' => '#F39C12', 'success' => '#27AE60', 'bg' => '#FFF3E0', 'card' => '#FFFFFF', 'text' => '#3B1F0A'],
    'midnight'  => ['label' => 'Midnight Purple',    'primary' => '#5B21B6', 'secondary' => '#C084FC', 'success' => '#34D399', 'bg' => '#F1EAFB', 'card' => '#FFFFFF', 'text' => '#1E1033'],
    'rose'      => ['label' => 'Rose Gold',          'primary' => '#BE185D', 'secondary' => '#F472B6', 'success' => '#10B981', 'bg' => '#FDEEF3', 'card' => '#FFFFFF', 'text' => '#33101E'],
    'ocean'     => ['label' => 'Ocean Teal',         'primary' => '#0E7490', 'secondary' => '#22D3EE', 'success' => '#16A34A', 'bg' => '#E6F6F8', 'card' => '#FFFFFF', 'text' => '#082A32'],
    'crimson'   => ['label' => 'Crimson Red',        'primary' => '#B91C1C', 'secondary' => '#F87171', 'success' => '#15803D', 'bg' => '#FCEAEA', 'card' => '#FFFFFF', 'text' => '#3A0C0C'],
    'forest'    => ['label' => 'Forest Green',       'primary' => '#166534', 'secondary' => '#A3E635', 'success' => '#059669', 'bg' => '#ECF6E9', 'card' => '#FFFFFF', 'text' => '#0D2412'],
    'graphite'  => ['label' => 'Graphite Dark',      'primary' => '#374151', 'secondary' => '#9CA3AF', 'success' => '#22C55E', 'bg' => '#EDEEF0', 'card' => '#FFFFFF', 'text' => '#111827'],
    'gold'      => ['label' => 'Luxury Gold',        'primary' => '#92400E', 'secondary' => '#FBBF24', 'success' => '#16A34A', 'bg' => '#FBF3DF', 'card' => '#FFFFFF', 'text' => '#2B1A05'],
    'slate'     => ['label' => 'Slate Blue',         'primary' => '#334155', 'secondary' => '#64748B', 'success' => '#22C55E', 'bg' => '#F1F5F9', 'card' => '#FFFFFF', 'text' => '#0F172A'],
    'coffee'    => ['label' => 'Coffee Brown',       'primary' => '#5C3A21', 'secondary' => '#B08968', 'success' => '#4D7C0F', 'bg' => '#F5EEE6', 'card' => '#FFFFFF', 'text' => '#2B1B0E'],
    'indigo'    => ['label' => 'Indigo Night',       'primary' => '#3730A3', 'secondary' => '#818CF8', 'success' => '#10B981', 'bg' => '#EEF0FD', 'card' => '#FFFFFF', 'text' => '#1E1B4B'],
    'cherry'    => ['label' => 'Cherry Blossom',     'primary' => '#9D174D', 'secondary' => '#FBCFE8', 'success' => '#16A34A', 'bg' => '#FFF1F6', 'card' => '#FFFFFF', 'text' => '#500724'],
    'sky'       => ['label' => 'Clear Sky',          'primary' => '#0369A1', 'secondary' => '#7DD3FC', 'success' => '#22C55E', 'bg' => '#EFF8FF', 'card' => '#FFFFFF', 'text' => '#0C4A6E'],
    // ---- Premium / dark glass ----
    'obsidian'  => ['label' => 'Obsidian Premium',   'primary' => '#0A0A12', 'secondary' => '#A855F7', 'success' => '#34D399', 'bg' => '#0F0F1A', 'card' => '#1A1A28', 'text' => '#F5F3FF'],
    'platinum'  => ['label' => 'Platinum Elite',     'primary' => '#1F2937', 'secondary' => '#D4AF37', 'success' => '#22C55E', 'bg' => '#111827', 'card' => '#1F2937', 'text' => '#F3F4F6'],
    'neon'      => ['label' => 'Neon Nights',        'primary' => '#6C63FF', 'secondary' => '#E040FB', 'success' => '#43E97B', 'bg' => '#0A0A12', 'card' => '#161622', 'text' => '#FFFFFF'],
    'diamond'   => ['label' => 'Diamond Blue',       'primary' => '#0B1F3A', 'secondary' => '#60A5FA', 'success' => '#2DD4BF', 'bg' => '#0F172A', 'card' => '#1A2740', 'text' => '#E5EDFF'],
    'velvet'    => ['label' => 'Velvet Wine',        'primary' => '#4A0E2E', 'secondary' => '#E8B4BC', 'success' => '#4ADE80', 'bg' => '#1A0812', 'card' => '#2A1420', 'text' => '#FBEAF0'],
    'carbon'    => ['label' => 'Carbon Black',       'primary' => '#18181B', 'secondary' => '#F59E0B', 'success' => '#22C55E', 'bg' => '#09090B', 'card' => '#18181B', 'text' => '#FAFAFA'],
    'cyber'     => ['label' => 'Cyber Teal',         'primary' => '#0D9488', 'secondary' => '#67E8F9', 'success' => '#34D399', 'bg' => '#042F2E', 'card' => '#0F3D3A', 'text' => '#CCFBF1'],
    'plum'      => ['label' => 'Royal Plum',         'primary' => '#581C87', 'secondary' => '#D8B4FE', 'success' => '#4ADE80', 'bg' => '#1E1035', 'card' => '#2C1650', 'text' => '#F3E8FF'],
    'garnet'    => ['label' => 'Garnet Dark',        'primary' => '#7F1D1D', 'secondary' => '#FCA5A5', 'success' => '#4ADE80', 'bg' => '#1C0A0A', 'card' => '#2B1212', 'text' => '#FEE2E2'],
    'steel'     => ['label' => 'Steel Blue Dark',    'primary' => '#1E293B', 'secondary' => '#38BDF8', 'success' => '#22C55E', 'bg' => '#0B1220', 'card' => '#16233A', 'text' => '#E2E8F0'],
    // ---- Vibrant / bold ----
    'flame'     => ['label' => 'Flame Red',          'primary' => '#DC2626', 'secondary' => '#FBBF24', 'success' => '#16A34A', 'bg' => '#FEF2F2', 'card' => '#FFFFFF', 'text' => '#450A0A'],
    'electric'  => ['label' => 'Electric Violet',    'primary' => '#7C3AED', 'secondary' => '#F0ABFC', 'success' => '#22C55E', 'bg' => '#F5F0FE', 'card' => '#FFFFFF', 'text' => '#2E1065'],
    'lime'      => ['label' => 'Lime Punch',         'primary' => '#4D7C0F', 'secondary' => '#BEF264', 'success' => '#16A34A', 'bg' => '#F7FEE7', 'card' => '#FFFFFF', 'text' => '#1A2E05'],
    'coral'     => ['label' => 'Coral Reef',         'primary' => '#EA580C', 'secondary' => '#FDBA74', 'success' => '#16A34A', 'bg' => '#FFF7ED', 'card' => '#FFFFFF', 'text' => '#431407'],
    'turquoise' => ['label' => 'Turquoise Pop',      'primary' => '#0891B2', 'secondary' => '#5EEAD4', 'success' => '#22C55E', 'bg' => '#ECFEFF', 'card' => '#FFFFFF', 'text' => '#083344'],
    'magenta'   => ['label' => 'Magenta Bold',       'primary' => '#A21CAF', 'secondary' => '#F0ABFC', 'success' => '#16A34A', 'bg' => '#FDF4FF', 'card' => '#FFFFFF', 'text' => '#4A044E'],
    'amber'     => ['label' => 'Amber Rush',         'primary' => '#B45309', 'secondary' => '#FCD34D', 'success' => '#16A34A', 'bg' => '#FFFBEB', 'card' => '#FFFFFF', 'text' => '#451A03'],
    'cobalt'    => ['label' => 'Cobalt Punch',       'primary' => '#1D4ED8', 'secondary' => '#93C5FD', 'success' => '#16A34A', 'bg' => '#EFF6FF', 'card' => '#FFFFFF', 'text' => '#1E3A8A'],
    'jade'      => ['label' => 'Jade Bright',        'primary' => '#047857', 'secondary' => '#6EE7B7', 'success' => '#059669', 'bg' => '#ECFDF5', 'card' => '#FFFFFF', 'text' => '#022C22'],
    'tangerine' => ['label' => 'Tangerine Zest',     'primary' => '#C2410C', 'secondary' => '#FED7AA', 'success' => '#16A34A', 'bg' => '#FFF7ED', 'card' => '#FFFFFF', 'text' => '#431407'],
    // ---- Pastel / soft ----
    'lavender'  => ['label' => 'Soft Lavender',      'primary' => '#7C3AED', 'secondary' => '#DDD6FE', 'success' => '#34D399', 'bg' => '#F5F3FF', 'card' => '#FFFFFF', 'text' => '#3B0764'],
    'blush'     => ['label' => 'Blush Pink',         'primary' => '#DB2777', 'secondary' => '#FBCFE8', 'success' => '#34D399', 'bg' => '#FDF2F8', 'card' => '#FFFFFF', 'text' => '#500724'],
    'sage'      => ['label' => 'Sage Whisper',       'primary' => '#4D7C0F', 'secondary' => '#D9F99D', 'success' => '#65A30D', 'bg' => '#F7FEE7', 'card' => '#FFFFFF', 'text' => '#1A2E05'],
    'powder'    => ['label' => 'Powder Blue',        'primary' => '#2563EB', 'secondary' => '#BFDBFE', 'success' => '#22C55E', 'bg' => '#EFF6FF', 'card' => '#FFFFFF', 'text' => '#1E3A8A'],
    'peach'     => ['label' => 'Peach Cream',        'primary' => '#EA580C', 'secondary' => '#FED7AA', 'success' => '#16A34A', 'bg' => '#FFF7ED', 'card' => '#FFFFFF', 'text' => '#7C2D12'],
    'mist'      => ['label' => 'Grey Mist',          'primary' => '#475569', 'secondary' => '#CBD5E1', 'success' => '#22C55E', 'bg' => '#F8FAFC', 'card' => '#FFFFFF', 'text' => '#1E293B'],
    'butter'    => ['label' => 'Buttercream',        'primary' => '#CA8A04', 'secondary' => '#FEF08A', 'success' => '#16A34A', 'bg' => '#FEFCE8', 'card' => '#FFFFFF', 'text' => '#422006'],
    'mint'      => ['label' => 'Fresh Mint',         'primary' => '#059669', 'secondary' => '#5EEAD4', 'success' => '#22C55E', 'bg' => '#F0FDFA', 'card' => '#FFFFFF', 'text' => '#053B32'],
];

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['save_customization'])) {
    $businessName = trim($_POST['checkout_business_name']);
    $primaryColor = trim($_POST['checkout_primary_color']);
    $secondaryColor = trim($_POST['checkout_secondary_color']);
    $successColor = trim($_POST['checkout_success_color']);
    $bgColor = trim($_POST['checkout_bg_color']);
    $cardBgColor = trim($_POST['checkout_card_bg_color']);
    $textColor = trim($_POST['checkout_text_color']);
    $template = isset($templates[$_POST['checkout_template']]) ? $_POST['checkout_template'] : 'emerald';
    $logoUrlInput = trim($_POST['checkout_logo_url']);
    $showQr = isset($_POST['checkout_show_qr']) ? 1 : 0;
    $showGpay = isset($_POST['checkout_show_googlepay']) ? 1 : 0;
    $showPhonepe = isset($_POST['checkout_show_phonepe']) ? 1 : 0;
    $showOtherUpi = isset($_POST['checkout_show_other_upi']) ? 1 : 0;

    $errors = [];
    if (!$showQr && !$showGpay && !$showPhonepe && !$showOtherUpi) {
        $errors[] = "At least one payment option (QR code or a pay button) must stay enabled, otherwise customers can't pay you.";
    }
    foreach (['checkout_primary_color' => $primaryColor, 'checkout_secondary_color' => $secondaryColor, 'checkout_success_color' => $successColor, 'checkout_bg_color' => $bgColor, 'checkout_card_bg_color' => $cardBgColor, 'checkout_text_color' => $textColor] as $fieldName => $val) {
        if ($val !== '' && !preg_match('/^#[0-9A-Fa-f]{6}$/', $val)) {
            $errors[] = "One of the colors isn't valid. Please use the color pickers.";
            break;
        }
    }

    $finalLogoUrl = $logoUrlInput;
    if (!empty($_FILES['checkout_logo_file']['name'])) {
        $file = $_FILES['checkout_logo_file'];
        $allowedExt = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png'];
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

        if ($file['error'] !== UPLOAD_ERR_OK) {
            $errors[] = "Logo upload failed, please try again.";
        } elseif ($file['size'] > 5 * 1024 * 1024) {
            $errors[] = "Logo file is too large (max 5MB).";
        } elseif (!isset($allowedExt[$ext])) {
            $errors[] = "Only PNG, JPG, and JPEG files are allowed.";
        } else {
            $imgInfo = @getimagesize($file['tmp_name']);
            if ($imgInfo === false || $imgInfo['mime'] !== $allowedExt[$ext]) {
                $errors[] = "That file doesn't look like a valid image.";
            } else {
                $newFileName = 'logo_' . $user_id . '_' . time() . '.' . $ext;
                if (!is_dir($uploadDir)) { @mkdir($uploadDir, 0755, true); }
                if (move_uploaded_file($file['tmp_name'], $uploadDir . $newFileName)) {
                    $finalLogoUrl = 'https://' . $_SERVER['SERVER_NAME'] . '/' . $uploadPublicPath . $newFileName;
                } else {
                    $errors[] = "Could not save the uploaded logo. Please check folder permissions.";
                }
            }
        }
    } elseif ($logoUrlInput !== '' && !filter_var($logoUrlInput, FILTER_VALIDATE_URL)) {
        $errors[] = "Please enter a valid Logo URL, or upload a file instead.";
    }

    if (!empty($errors)) {
        echo '<script>Swal.fire({title:"Please fix the following", html:"' . implode('<br>', array_map('htmlspecialchars', $errors)) . '", icon:"error"});</script>';
    } else {
        $stmt = $conn->prepare("UPDATE users SET checkout_business_name=?, checkout_primary_color=?, checkout_secondary_color=?, checkout_success_color=?, checkout_bg_color=?, checkout_card_bg_color=?, checkout_text_color=?, checkout_template=?, checkout_logo_url=?, checkout_show_qr=?, checkout_show_googlepay=?, checkout_show_phonepe=?, checkout_show_other_upi=? WHERE id=?");
        if ($stmt === false) {
            echo '<script>Swal.fire({title:"Setup needed", text:"Please run sql/RUN_THIS_ALL_IN_ONE.sql in phpMyAdmin first, then try saving again.", icon:"error"});</script>';
        } else {
            $nameParam = ($businessName === '') ? null : $businessName;
            $logoParam = ($finalLogoUrl === '') ? null : $finalLogoUrl;
            $stmt->bind_param("sssssssssiiiii", $nameParam, $primaryColor, $secondaryColor, $successColor, $bgColor, $cardBgColor, $textColor, $template, $logoParam, $showQr, $showGpay, $showPhonepe, $showOtherUpi, $user_id);
            $stmt->execute();
            $stmt->close();
            echo '<script>Swal.fire({title:"Saved!", text:"Your payment page customization has been updated.", icon:"success"}).then(()=>{ window.location.href = "customize_page"; });</script>';
        }
    }
}

$freshResult = $conn->query("SELECT checkout_logo_url, checkout_primary_color, checkout_secondary_color, checkout_success_color, checkout_bg_color, checkout_card_bg_color, checkout_text_color, checkout_template, checkout_business_name, checkout_show_qr, checkout_show_googlepay, checkout_show_phonepe, checkout_show_other_upi, name FROM users WHERE id = " . (int)$user_id);

$sqlSetupNeeded = ($freshResult === false);
if (!$sqlSetupNeeded) {
    $fresh = $freshResult->fetch_assoc();
} else {
    $fresh = [];
}

$currentLogo = $fresh['checkout_logo_url'] ?? '';
$currentPrimary = $fresh['checkout_primary_color'] ?: '#0F6B5C';
$currentSecondary = $fresh['checkout_secondary_color'] ?: '#E8A33D';
$currentSuccess = $fresh['checkout_success_color'] ?: '#1FAA59';
$currentBg = $fresh['checkout_bg_color'] ?: '#EAF3F0';
$currentCardBg = $fresh['checkout_card_bg_color'] ?: '#F4F6F5';
$currentText = $fresh['checkout_text_color'] ?: '#0B1F1C';
$currentTemplate = $fresh['checkout_template'] ?: 'emerald';
$currentName = $fresh['checkout_business_name'] ?? '';
$accountName = $fresh['name'] ?? '';
$showQr = $fresh['checkout_show_qr'] ?? 1;
$showGpay = $fresh['checkout_show_googlepay'] ?? 1;
$showPhonepe = $fresh['checkout_show_phonepe'] ?? 1;
$showOtherUpi = $fresh['checkout_show_other_upi'] ?? 1;
?>

<style>
    :root{
        --p:#6c63ff; --p2:#e040fb;
        --g: linear-gradient(135deg,#6c63ff,#e040fb);
        --success:#43e97b; --danger:#ff6584; --warning:#f5b93b; --info:#3ea6ff;
    }
    *{box-sizing:border-box}
    html, body, .content-wrapper{ background:#0a0a12 !important; }
    body{ font-family:'Inter',sans-serif; color:#fff; min-height:100vh; }
    .content-wrapper{min-height:100vh}
    .container-fluid{padding:20px;max-width:1400px;margin:0 auto}

    .dashboard-card{
        background:rgba(255,255,255,.04); backdrop-filter:blur(20px);
        border:1px solid rgba(255,255,255,.08); border-radius:20px;
        margin-bottom:20px; overflow:hidden;
    }
    .card-header{
        padding:18px 22px; border-bottom:1px solid rgba(255,255,255,.07);
        display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:14px;
    }
    .card-header h3{font-size:1.05rem;font-weight:700;margin:0;color:#fff}
    .settings-header{display:flex;align-items:center;gap:14px;}
    .settings-icon{
        width:44px;height:44px;border-radius:12px;flex-shrink:0;
        display:flex;align-items:center;justify-content:center;font-size:1.15rem;color:#fff;
        background:var(--g);
    }
    .settings-title{font-size:1.05rem;font-weight:700;color:#fff;margin:0;}
    .settings-subtitle{font-size:.82rem;color:rgba(255,255,255,.45);margin-top:2px;}

    /* Modern toggle switch, matching the polished pill-style seen elsewhere */
    .toggle-row{
        display:flex;align-items:center;justify-content:space-between;gap:16px;
        padding:14px 16px;background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.07);
        border-radius:14px;margin-bottom:12px;
    }
    .toggle-row .toggle-label{font-weight:600;color:#fff;font-size:.92rem;}
    .toggle-row .toggle-sub{font-size:.78rem;color:rgba(255,255,255,.4);margin-top:2px;}
    .toggle-switch{
        position:relative;display:inline-block;width:50px;height:28px;flex-shrink:0;
    }
    .toggle-switch input{opacity:0;width:0;height:0;}
    .toggle-slider{
        position:absolute;cursor:pointer;inset:0;background:rgba(255,255,255,.15);
        transition:.25s;border-radius:34px;
    }
    .toggle-slider:before{
        position:absolute;content:"";height:22px;width:22px;left:3px;bottom:3px;
        background:#fff;transition:.25s;border-radius:50%;
        box-shadow:0 2px 4px rgba(0,0,0,.3);
    }
    .toggle-switch input:checked + .toggle-slider{background:var(--g);}
    .toggle-switch input:checked + .toggle-slider:before{transform:translateX(22px);}
    .card-body{padding:22px}

    label{color:rgba(255,255,255,.8);font-weight:600;font-size:.88rem;margin-bottom:6px;display:block;}
    small.text-muted{color:rgba(255,255,255,.4) !important;}
    .form-control{
        background:rgba(255,255,255,.05); border:1px solid rgba(255,255,255,.12);
        color:#fff; border-radius:10px;
    }
    .form-control:focus{background:rgba(255,255,255,.08);color:#fff;border-color:var(--p);box-shadow:0 0 0 .2rem rgba(108,99,255,.2);}
    .form-control::placeholder{color:rgba(255,255,255,.3);}
    .form-control[type="file"]{padding:8px;color:rgba(255,255,255,.7);}
    .form-control[type="file"]::file-selector-button{
        background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.15);color:#fff;
        border-radius:7px;padding:6px 12px;margin-right:10px;font-weight:600;font-size:.82rem;cursor:pointer;
    }
    /* Some Android OS skins (MIUI/One UI) override <select> text color with
       their own system gray regardless of author CSS, making the selected
       template name unreadable. Removing native appearance and drawing a
       custom arrow guarantees full control over the color on every device. */
    select.form-control{
        color:#fff !important; -webkit-appearance:none; -moz-appearance:none; appearance:none;
        background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='14' height='9' viewBox='0 0 14 9'><path d='M1 1l6 6 6-6' stroke='%23a99bff' stroke-width='2' fill='none' stroke-linecap='round' stroke-linejoin='round'/></svg>");
        background-repeat:no-repeat; background-position:right 14px center; padding-right:36px;
    }
    select.form-control option{background:#15151f;color:#fff;}

    .alert-danger{
        background:rgba(255,101,132,.1) !important; border:1px solid rgba(255,101,132,.3) !important;
        color:#ffb3c1 !important; border-radius:14px !important; padding:16px 18px !important;
    }
    .alert-danger code{background:rgba(255,255,255,.1);padding:2px 6px;border-radius:5px;color:#ffd7de}

    .form-check-input{background-color:rgba(255,255,255,.08);border-color:rgba(255,255,255,.25);}
    .form-check-input:checked{background-color:var(--p);border-color:var(--p);}
    .form-check-label{color:rgba(255,255,255,.85);}

    .btn-primary{background:var(--g);border:none;border-radius:10px;padding:10px 22px;font-weight:600;}
    .btn-primary:hover{opacity:.9;}

    hr{border-color:rgba(255,255,255,.08);}
    h5, h6{color:#fff;}

    .color-swatch-row{display:flex;align-items:center;gap:10px;}
    .color-swatch-row input[type=color]{width:56px;height:42px;padding:2px;border-radius:8px;border:1px solid rgba(255,255,255,.15);background:transparent;}
    .color-hex-label{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.12);color:rgba(255,255,255,.75);padding:8px 12px;border-radius:8px;font-size:.85rem;min-width:100px;text-align:center;}

    .template-swatches{display:flex;gap:4px;}
    .template-swatches span{width:16px;height:16px;border-radius:4px;display:inline-block;}

    .preview-box{
        background:var(--preview-bg,#EAF3F0); border-radius:16px; padding:18px;
        border:1px solid rgba(255,255,255,.08);
    }
    .preview-header{
        background:var(--preview-primary,#0F6B5C); border-radius:12px; padding:14px 16px;
        display:flex; align-items:center; gap:12px; margin-bottom:14px;
    }
    .preview-header img{width:40px;height:40px;border-radius:9px;object-fit:cover;background:#fff;}
    .preview-header .name{color:#fff;font-weight:700;font-size:1rem;}
    .preview-header .verified{color:rgba(255,255,255,.85);font-size:.78rem;}
    .preview-amount-bar{height:4px;border-radius:4px;background:var(--preview-secondary,#E8A33D);margin-bottom:14px;}
    .preview-card{background:var(--preview-card,#FFFFFF);border-radius:10px;padding:14px;margin-bottom:14px;box-shadow:0 2px 8px rgba(0,0,0,.06);}
    .preview-btn{
        background:var(--preview-primary,#0F6B5C);color:#fff;padding:10px 16px;border-radius:10px;
        text-align:center;font-weight:600;font-size:.85rem;
    }
    .save-btn{
        display:inline-flex;align-items:center;gap:8px;box-shadow:0 6px 18px rgba(108,99,255,.3);
    }
    .save-btn:hover{transform:translateY(-1px);box-shadow:0 10px 24px rgba(108,99,255,.45)}
</style>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<div class="container-fluid" style="padding-bottom:0">
    <div style="display:flex;align-items:center;gap:12px;margin-bottom:4px">
        <div class="settings-icon" style="width:38px;height:38px;font-size:16px"><i class="fas fa-swatchbook"></i></div>
        <h1 style="font-size:1.5rem;font-weight:800;color:#fff;margin:0">Customize Payment Page</h1>
    </div>
    <p style="color:rgba(255,255,255,.45);font-size:.85rem;margin:2px 0 0 50px">Control how your checkout page looks to customers</p>
</div>

<div class="container-fluid py-3">

<?php if ($sqlSetupNeeded): ?>
    <div class="dashboard-card"><div class="card-body">
        <div class="alert alert-danger mb-0">
            <b>Setup needed:</b> This page needs a few extra database columns that haven't
            been added yet. Please run the latest <code>sql/upgrade.sql</code> (or
            <code>sql/upgrade_new_only2.sql</code>) in phpMyAdmin - it's safe to re-run and
            won't touch any existing data - then reload this page.
            <br><small>Technical detail: <?= htmlspecialchars($conn->error) ?></small>
        </div>
    </div></div>
<?php else: ?>

    <div class="dashboard-card">
        <div class="card-header">
            <div class="settings-header">
                <div class="settings-icon"><i class="fas fa-circle-info"></i></div>
                <div>
                    <div class="settings-title">About this page</div>
                    <div class="settings-subtitle">How this affects your customers</div>
                </div>
            </div>
        </div>
        <div class="card-body">
            <p class="text-muted mb-0">These settings control how your customers see the payment page they land on
            when they pay you (currently applies to the FamPay and Paytm checkout pages). Changes appear immediately on your next payment link.</p>
        </div>
    </div>

    <form method="POST" action="" enctype="multipart/form-data" id="customizeForm">

        <div class="dashboard-card">
            <div class="card-header">
                <div class="settings-header">
                    <div class="settings-icon"><i class="fas fa-palette"></i></div>
                    <div>
                        <div class="settings-title">Template</div>
                        <div class="settings-subtitle">Choose from ready-made color themes</div>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <label>Choose a Starting Template</label>
                <select class="form-control" id="templateSelect" name="checkout_template" style="max-width:360px;">
                    <?php foreach ($templates as $key => $t): ?>
                        <option value="<?= $key ?>" data-primary="<?= $t['primary'] ?>" data-secondary="<?= $t['secondary'] ?>" data-success="<?= $t['success'] ?>" data-bg="<?= $t['bg'] ?>" data-card="<?= $t['card'] ?>" data-text="<?= $t['text'] ?>" <?= $currentTemplate === $key ? 'selected' : '' ?>>
                            <?= $t['label'] ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <small class="text-muted d-block mt-2">Picking a template fills in all the colors below - you can still fine-tune any of them afterward.</small>
            </div>
        </div>

        <div class="dashboard-card">
            <div class="card-header">
                <div class="settings-header">
                    <div class="settings-icon"><i class="fas fa-building"></i></div>
                    <div>
                        <div class="settings-title">Branding</div>
                        <div class="settings-subtitle">Upload your logo and set your business name</div>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>Business Display Name</label>
                        <input type="text" name="checkout_business_name" class="form-control"
                               placeholder="<?= htmlspecialchars($accountName) ?: 'Your Business Name' ?>"
                               value="<?= htmlspecialchars($currentName) ?>">
                        <small class="text-muted">Leave blank to use your account name (<?= htmlspecialchars($accountName) ?>).</small>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>Logo Image URL</label>
                        <input type="url" name="checkout_logo_url" id="logoUrlInput" class="form-control"
                               placeholder="https://example.com/your-logo.png"
                               value="<?= htmlspecialchars($currentLogo) ?>">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>Or Upload a Logo</label>
                        <input type="file" name="checkout_logo_file" id="logoFileInput" class="form-control" accept=".png,.jpg,.jpeg">
                        <small class="text-muted">PNG/JPG/JPEG, max 5MB. If you upload a file, it's used instead of the URL.</small>
                    </div>
                </div>
            </div>
        </div>

        <div class="dashboard-card">
            <div class="card-header">
                <div class="settings-header">
                    <div class="settings-icon"><i class="fas fa-fill-drip"></i></div>
                    <div>
                        <div class="settings-title">Colors</div>
                        <div class="settings-subtitle">Customize the color scheme of your payment page</div>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label>Primary Color</label>
                        <div class="color-swatch-row">
                            <input type="color" class="colorInput" id="primaryColor" name="checkout_primary_color" value="<?= htmlspecialchars($currentPrimary) ?>">
                            <span class="color-hex-label" id="primaryColorHex"><?= htmlspecialchars($currentPrimary) ?></span>
                        </div>
                        <small class="text-muted">Header background &amp; main buttons.</small>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label>Secondary / Accent Color</label>
                        <div class="color-swatch-row">
                            <input type="color" class="colorInput" id="secondaryColor" name="checkout_secondary_color" value="<?= htmlspecialchars($currentSecondary) ?>">
                            <span class="color-hex-label" id="secondaryColorHex"><?= htmlspecialchars($currentSecondary) ?></span>
                        </div>
                        <small class="text-muted">The thin progress/expiry bar.</small>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label>Success Color</label>
                        <div class="color-swatch-row">
                            <input type="color" class="colorInput" id="successColor" name="checkout_success_color" value="<?= htmlspecialchars($currentSuccess) ?>">
                            <span class="color-hex-label" id="successColorHex"><?= htmlspecialchars($currentSuccess) ?></span>
                        </div>
                        <small class="text-muted">"Scan with any UPI app" dot &amp; success screen.</small>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label>Page Background</label>
                        <div class="color-swatch-row">
                            <input type="color" class="colorInput" id="bgColor" name="checkout_bg_color" value="<?= htmlspecialchars($currentBg) ?>">
                            <span class="color-hex-label" id="bgColorHex"><?= htmlspecialchars($currentBg) ?></span>
                        </div>
                        <small class="text-muted">Overall page backdrop.</small>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label>Card / Box Background</label>
                        <div class="color-swatch-row">
                            <input type="color" class="colorInput" id="cardBgColor" name="checkout_card_bg_color" value="<?= htmlspecialchars($currentCardBg) ?>">
                            <span class="color-hex-label" id="cardBgColorHex"><?= htmlspecialchars($currentCardBg) ?></span>
                        </div>
                        <small class="text-muted">Background of the amount box, QR card etc. - keep it lighter/darker than Page Background so text stays readable.</small>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label>Text Color</label>
                        <div class="color-swatch-row">
                            <input type="color" class="colorInput" id="textColor" name="checkout_text_color" value="<?= htmlspecialchars($currentText) ?>">
                            <span class="color-hex-label" id="textColorHex"><?= htmlspecialchars($currentText) ?></span>
                        </div>
                        <small class="text-muted">Main heading &amp; body text.</small>
                    </div>
                </div>
            </div>
        </div>

        <div class="dashboard-card">
            <div class="card-header">
                <div class="settings-header">
                    <div class="settings-icon"><i class="fas fa-toggle-on"></i></div>
                    <div>
                        <div class="settings-title">Payment Page Elements</div>
                        <div class="settings-subtitle">Control what your customers see and can use to pay</div>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="toggle-row">
                    <div>
                        <div class="toggle-label">Show QR Code</div>
                        <div class="toggle-sub">Lets customers scan to pay with any UPI app</div>
                    </div>
                    <label class="toggle-switch">
                        <input type="checkbox" name="checkout_show_qr" id="showQr" value="1" <?= $showQr ? 'checked' : '' ?>>
                        <span class="toggle-slider"></span>
                    </label>
                </div>
                <div class="toggle-row">
                    <div>
                        <div class="toggle-label">Show Google Pay Button</div>
                        <div class="toggle-sub">One-tap button that opens Google Pay directly</div>
                    </div>
                    <label class="toggle-switch">
                        <input type="checkbox" name="checkout_show_googlepay" id="showGpay" value="1" <?= $showGpay ? 'checked' : '' ?>>
                        <span class="toggle-slider"></span>
                    </label>
                </div>
                <div class="toggle-row">
                    <div>
                        <div class="toggle-label">Show PhonePe Button</div>
                        <div class="toggle-sub">One-tap button that opens PhonePe directly</div>
                    </div>
                    <label class="toggle-switch">
                        <input type="checkbox" name="checkout_show_phonepe" id="showPhonepe" value="1" <?= $showPhonepe ? 'checked' : '' ?>>
                        <span class="toggle-slider"></span>
                    </label>
                </div>
                <div class="toggle-row">
                    <div>
                        <div class="toggle-label">Show "Other UPI Apps / BHIM" Button</div>
                        <div class="toggle-sub">Covers Paytm, BHIM, and any other UPI app</div>
                    </div>
                    <label class="toggle-switch">
                        <input type="checkbox" name="checkout_show_other_upi" id="showOtherUpi" value="1" <?= $showOtherUpi ? 'checked' : '' ?>>
                        <span class="toggle-slider"></span>
                    </label>
                </div>
                <small class="text-muted">At least one of the four options above must stay on.</small>
            </div>
        </div>

        <div class="dashboard-card">
            <div class="card-header">
                <div class="settings-header">
                    <div class="settings-icon"><i class="fas fa-eye"></i></div>
                    <div>
                        <div class="settings-title">Preview</div>
                        <div class="settings-subtitle">Dekho aapka payment page kaisa dikhega - naye tab me, bina save kiye</div>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <button type="button" class="btn btn-primary save-btn" id="openPreviewBtn" style="width:auto;padding:12px 28px"><i class="fas fa-arrow-up-right-from-square"></i> Preview Payment Page</button>
            </div>
        </div>

        <button type="submit" name="save_customization" class="btn btn-primary save-btn"><i class="fas fa-floppy-disk"></i> Save Changes</button>
    </form>

    <form id="previewForm" method="POST" action="customize_preview" target="_blank" style="display:none">
        <input type="hidden" name="business_name" id="pv_business_name">
        <input type="hidden" name="primary_color" id="pv_primary_color">
        <input type="hidden" name="secondary_color" id="pv_secondary_color">
        <input type="hidden" name="success_color" id="pv_success_color">
        <input type="hidden" name="bg_color" id="pv_bg_color">
        <input type="hidden" name="card_bg_color" id="pv_card_bg_color">
        <input type="hidden" name="text_color" id="pv_text_color">
        <input type="hidden" name="logo_url" id="pv_logo_url">
        <input type="hidden" name="show_qr" id="pv_show_qr">
        <input type="hidden" name="show_googlepay" id="pv_show_googlepay">
        <input type="hidden" name="show_phonepe" id="pv_show_phonepe">
        <input type="hidden" name="show_other_upi" id="pv_show_other_upi">
    </form>
    <script>
        document.getElementById('openPreviewBtn').addEventListener('click', function(){
            var nameField = document.querySelector('input[name="checkout_business_name"]');
            document.getElementById('pv_business_name').value   = (nameField && nameField.value) ? nameField.value : '<?= htmlspecialchars($currentName ?: $accountName, ENT_QUOTES) ?>';
            document.getElementById('pv_primary_color').value   = document.getElementById('primaryColor').value;
            document.getElementById('pv_secondary_color').value = document.getElementById('secondaryColor').value;
            document.getElementById('pv_success_color').value   = document.getElementById('successColor').value;
            document.getElementById('pv_bg_color').value        = document.getElementById('bgColor').value;
            document.getElementById('pv_card_bg_color').value   = document.getElementById('cardBgColor').value;
            document.getElementById('pv_text_color').value      = document.getElementById('textColor').value;
            document.getElementById('pv_logo_url').value        = document.getElementById('logoUrlInput') ? document.getElementById('logoUrlInput').value : '';
            document.getElementById('pv_show_qr').value          = document.getElementById('showQr') && document.getElementById('showQr').checked ? '1' : '0';
            document.getElementById('pv_show_googlepay').value   = document.getElementById('showGpay') && document.getElementById('showGpay').checked ? '1' : '0';
            document.getElementById('pv_show_phonepe').value     = document.getElementById('showPhonepe') && document.getElementById('showPhonepe').checked ? '1' : '0';
            document.getElementById('pv_show_other_upi').value   = document.getElementById('showOtherUpi') && document.getElementById('showOtherUpi').checked ? '1' : '0';
            document.getElementById('previewForm').submit();
        });
    </script>

<?php endif; ?>
</div>

<script>
var templates = <?= json_encode($templates) ?>;

function applyPreview(){
    var primary = document.getElementById('primaryColor').value;
    var secondary = document.getElementById('secondaryColor').value;
    var success = document.getElementById('successColor').value;
    var bg = document.getElementById('bgColor').value;
    var cardBg = document.getElementById('cardBgColor').value;

    document.getElementById('primaryColorHex').textContent = primary;
    document.getElementById('secondaryColorHex').textContent = secondary;
    document.getElementById('successColorHex').textContent = success;
    document.getElementById('bgColorHex').textContent = bg;
    document.getElementById('cardBgColorHex').textContent = cardBg;
    document.getElementById('textColorHex').textContent = document.getElementById('textColor').value;
}

document.querySelectorAll('.colorInput').forEach(function(el){
    el.addEventListener('input', applyPreview);
});

document.getElementById('templateSelect').addEventListener('change', function(){
    var opt = this.options[this.selectedIndex];
    document.getElementById('primaryColor').value = opt.dataset.primary;
    document.getElementById('secondaryColor').value = opt.dataset.secondary;
    document.getElementById('successColor').value = opt.dataset.success;
    document.getElementById('bgColor').value = opt.dataset.bg;
    document.getElementById('cardBgColor').value = opt.dataset.card;
    document.getElementById('textColor').value = opt.dataset.text;
    applyPreview();
});

applyPreview();
</script>

</body>
<script src="./assets/vendors/jquery/dist/jquery.min.js"></script>
<script src="assets/js/core/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="assets/js/app.min.js"></script>
</html>
