<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once '../config.php';

if (!isset($_SESSION['admin_id'])) { header("Location: login.php"); exit; }

$message = ''; $msgType = 'success';
global $pdo;

// Create table if not exists (One-time setup)
$pdo->exec("CREATE TABLE IF NOT EXISTS `ui_images` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image_key` varchar(50) NOT NULL UNIQUE,
  `base64_data` longtext NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

// =====================================
// UPLOAD LOGIC (FIXED FOR ALL HOSTINGS)
// =====================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_image'])) {
    // FIX 1: Check if image_key is properly set
    $imgKey = isset($_POST['image_key']) ? $_POST['image_key'] : ''; 
    
    if (!empty($imgKey) && !empty($_FILES['custom_image']['tmp_name'])) {
        $fileData = file_get_contents($_FILES['custom_image']['tmp_name']);
        
        // FIX 2: Replaced mime_content_type() with hosting-friendly methods
        $imageInfo = getimagesize($_FILES['custom_image']['tmp_name']);
        if ($imageInfo !== false && isset($imageInfo['mime'])) {
            $mimeType = $imageInfo['mime']; // Best method
        } else {
            $mimeType = $_FILES['custom_image']['type']; // Fallback browser method
        }
        
        // Convert to Base64
        $base64String = 'data:' . $mimeType . ';base64,' . base64_encode($fileData);
        
        $stmt = $pdo->prepare("INSERT INTO ui_images (image_key, base64_data) VALUES (?, ?) ON DUPLICATE KEY UPDATE base64_data = VALUES(base64_data)");
        
        if ($stmt->execute([$imgKey, $base64String])) {
            $message = strtoupper(str_replace('_', ' ', $imgKey)) . " Updated Successfully!";
        } else {
            $message = "Failed to update database."; $msgType = "error";
        }
    } else {
        $message = "Please select an image first."; $msgType = "error";
    }
}

// Fetch saved images for preview
$stmt = $pdo->query("SELECT image_key, base64_data FROM ui_images");
$savedImages = [];
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    $savedImages[$row['image_key']] = $row['base64_data'];
}

$pageTitle = "Base64 Image Manager";
require_once 'includes/header.php';
?>

<style>
    .img-upload-card { background: #fff; border-radius: 12px; padding: 20px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); border: 1px solid #eee; height: 100%; text-align: center;}
    .preview-box { width: 80px; height: 80px; border-radius: 15px; border: 2px dashed #1E88E5; padding: 5px; margin: 0 auto 15px; display: flex; align-items: center; justify-content: center; background: #f9f9f9; overflow: hidden;}
    .preview-box.circle { border-radius: 50%; }
    .preview-box img { width: 100%; height: 100%; object-fit: contain; }
    .upload-btn { background: #1e3c72; border: none; font-weight: bold; font-size: 12px;}
    .card-title-ui { font-weight: 800; color: #333; font-size: 13px; margin-bottom: 5px; text-transform: uppercase;}
</style>

<?php if($message): ?>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>Swal.fire({ toast: true, position: 'top-end', icon: '<?= $msgType ?>', title: '<?= $message ?>', showConfirmButton: false, timer: 3000 });</script>
<?php endif; ?>

<h4 class="fw-bold mb-3"><i class="fas fa-database text-danger"></i> Profile Elements Controller</h4>
<p class="text-muted mb-4">Images uploaded here are saved directly into the database. They will automatically show up on the user's profile page.</p>

<div class="row g-3">
    <?php
    $uiElements = [
        ['name' => 'face', 'title' => 'Profile Avatar', 'type' => 'circle'],
        ['name' => 'icon_wallet', 'title' => 'Wallet Icon', 'type' => 'box'],
        ['name' => 'icon_deposit', 'title' => 'Deposit Icon', 'type' => 'box'],
        ['name' => 'icon_withdraw', 'title' => 'Withdraw Icon', 'type' => 'box'],
        ['name' => 'icon_vip', 'title' => 'VIP Icon', 'type' => 'box'],
        ['name' => 'icon_game', 'title' => 'Game History', 'type' => 'box'],
        ['name' => 'icon_trans', 'title' => 'Transaction', 'type' => 'box']
    ];

    foreach($uiElements as $item): 
        $currentImg = isset($savedImages[$item['name']]) ? $savedImages[$item['name']] : '';
    ?>
        <div class="col-6 col-md-3">
            <div class="img-upload-card">
                <h5 class="card-title-ui"><?= $item['title'] ?></h5>
                
                <div class="preview-box <?= $item['type'] ?>">
                    <?php if($currentImg): ?>
                        <img src="<?= $currentImg ?>">
                    <?php else: ?>
                        <span style="font-size:10px; color:#aaa;">No Image</span>
                    <?php endif; ?>
                </div>

                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="image_key" value="<?= $item['name'] ?>">
                    <input type="file" name="custom_image" class="form-control form-control-sm mb-2" accept="image/*" required>
                    <button type="submit" name="upload_image" class="btn btn-primary btn-sm upload-btn w-100"><i class="fas fa-upload"></i> Upload</button>
                </form>
            </div>
        </div>
    <?php endforeach; ?>
</div>

<?php require_once 'includes/footer.php'; ?>