<?php
require_once __DIR__ . '/../includes/functions.php';
requireAdmin();

header('Content-Type: application/json');

// ── Handle image upload ───────────────────────────────────
if (!empty($_FILES['card_bg_image_file']['tmp_name'])) {
    $file    = $_FILES['card_bg_image_file'];
    $allowed = ['image/jpeg','image/png','image/webp','image/gif'];
    $maxSize = 3 * 1024 * 1024; // 3 MB

    if (!in_array($file['type'], $allowed)) {
        jsonResponse(['success'=>false,'error'=>'Only JPG, PNG, WEBP or GIF images allowed.']);
    }
    if ($file['size'] > $maxSize) {
        jsonResponse(['success'=>false,'error'=>'Image must be under 3 MB.']);
    }
    // Store as base64 data URI — no filesystem dependency
    $data    = file_get_contents($file['tmp_name']);
    $base64  = 'data:' . $file['type'] . ';base64,' . base64_encode($data);
    setSetting('card_bg_image', $base64);
    setSetting('card_bg_type',  'image');
    jsonResponse(['success'=>true,'message'=>'Background image uploaded.','preview'=>$base64]);
}

// ── Handle clear image ────────────────────────────────────
if (isset($_POST['clear_image'])) {
    setSetting('card_bg_image', '');
    setSetting('card_bg_type',  'gradient');
    jsonResponse(['success'=>true,'message'=>'Background image cleared.']);
}

// ── Handle design settings save ───────────────────────────
$allowed = [
    'card_bg_type',
    'card_gradient_dir',
    'card_gradient_color1',
    'card_gradient_color2',
    'card_gradient_color3',
    'card_text_color',
    'card_accent_color',
    'card_logo_icon',
    'card_show_shimmer',
    'card_label_text',
    'card_subtitle_text',
    'card_qr_text',
];

// Ensure settings exist in DB (safe for old installs)
$db = getDB();
$defaults = [
    'card_bg_type'         => 'gradient',
    'card_gradient_dir'    => '135deg',
    'card_gradient_color1' => '#1e3a8a',
    'card_gradient_color2' => '#1d4ed8',
    'card_gradient_color3' => '#0ea5e9',
    'card_text_color'      => '#ffffff',
    'card_accent_color'    => '#facc15',
    'card_bg_image'        => '',
    'card_logo_icon'       => 'star-fill',
    'card_show_shimmer'    => '1',
    'card_label_text'      => 'MEMBER CARD',
    'card_subtitle_text'   => 'REWARDS MEMBER',
    'card_qr_text'         => '',
];
foreach ($defaults as $k => $v) {
    $db->prepare("INSERT IGNORE INTO settings (setting_key,setting_value,setting_label) VALUES (?,?,?)")
       ->execute([$k, $v, $k]);
}

foreach ($allowed as $key) {
    if (isset($_POST[$key])) {
        $val = trim($_POST[$key]);
        // Sanitise color values
        if (strpos($key, 'color') !== false || $key === 'card_gradient_dir') {
            $val = preg_replace('/[^a-zA-Z0-9#(),%. -]/', '', $val);
        }
        // Sanitise icon name (alphanumeric + dash only)
        if ($key === 'card_logo_icon') {
            $val = preg_replace('/[^a-z0-9\-]/', '', strtolower($val));
        }
        // Boolean
        if ($key === 'card_show_shimmer') {
            $val = $val === '1' ? '1' : '0';
        }
        setSetting($key, $val);
    }
}

jsonResponse(['success'=>true, 'message'=>'Card design saved successfully!']);
