<?php
// Database connection
$db = new SQLite3('./api/.db.db');

// Table name
$table_name = "studiolivecode_fundo";

// Current file var
$base_file = basename($_SERVER["SCRIPT_NAME"]);

// Create table if not exists
$db->exec("CREATE TABLE IF NOT EXISTS {$table_name}(
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
    filename TEXT UNIQUE, 
    filepath TEXT, 
    uploaded_at DATETIME DEFAULT CURRENT_TIMESTAMP
)");

// Directory for uploads
$upload_dir = 'public/images/';
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0755, true);
}

// Handle file upload
if (isset($_POST['submit'])) {
    if (isset($_FILES['fundo']) && $_FILES['fundo']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['fundo'];
        
        // Validate file type
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
        $file_info = finfo_open(FILEINFO_MIME_TYPE);
        $mime_type = finfo_file($file_info, $file['tmp_name']);
        finfo_close($file_info);
        
        if (!in_array($mime_type, $allowed_types)) {
            die('Error: Only JPG, PNG, and GIF files are allowed.');
        }
        
        // Definir nome fixo como bg.jpg
        $filename = 'bg.jpg';
        $filepath = $upload_dir . $filename;
        
        // Delete old bg if exists
        $res = $db->query("SELECT filepath FROM {$table_name} LIMIT 1");
        if ($row = $res->fetchArray()) {
            if (file_exists($row['filepath'])) {
                unlink($row['filepath']);
            }
        }
        
        // Delete any existing bg.jpg in the directory
        if (file_exists($filepath)) {
            unlink($filepath);
        }
        
        // Se for JPG, apenas move o arquivo
        if ($mime_type == 'image/jpeg') {
            if (move_uploaded_file($file['tmp_name'], $filepath)) {
                // Success
            } else {
                die('Error: Failed to move uploaded file.');
            }
        } 
        // Se for PNG ou GIF, converte para JPG
        else {
            if ($mime_type == 'image/png') {
                $image = imagecreatefrompng($file['tmp_name']);
            } else if ($mime_type == 'image/gif') {
                $image = imagecreatefromgif($file['tmp_name']);
            }
            
            // Criar fundo branco para imagens com transparência
            $width = imagesx($image);
            $height = imagesy($image);
            $jpg_image = imagecreatetruecolor($width, $height);
            $white = imagecolorallocate($jpg_image, 255, 255, 255);
            imagefill($jpg_image, 0, 0, $white);
            imagecopy($jpg_image, $image, 0, 0, 0, 0, $width, $height);
            
            // Salvar como JPG com qualidade 90%
            if (!imagejpeg($jpg_image, $filepath, 90)) {
                die('Error: Failed to convert image to JPG.');
            }
            
            // Liberar memória
            imagedestroy($image);
            imagedestroy($jpg_image);
        }
        
        // Clear the table before inserting new record
        $db->exec("DELETE FROM {$table_name}");
        
        // Insert into database
        $stmt = $db->prepare("INSERT INTO {$table_name}(filename, filepath) VALUES(:filename, :filepath)");
        $stmt->bindValue(':filename', $filename, SQLITE3_TEXT);
        $stmt->bindValue(':filepath', $filepath, SQLITE3_TEXT);
        $stmt->execute();
        
        header("Location: {$base_file}?status=1");
        exit();
    } else {
        die('Error: No file uploaded or upload error.');
    }
}

// Delete fundo
if (isset($_GET['delete'])) {
    $res = $db->query("SELECT filepath FROM {$table_name} WHERE id = " . (int)$_GET['delete']);
    if ($row = $res->fetchArray()) {
        if (file_exists($row['filepath'])) {
            unlink($row['filepath']);
        }
    }
    $db->exec("DELETE FROM {$table_name} WHERE id = " . (int)$_GET['delete']);
    header("Location: {$base_file}?status=1");
}

include ('includes/studiolivheaderecode.php');

// Get current fundo
$current_fundo = null;
$res = $db->query("SELECT * FROM {$table_name} ORDER BY uploaded_at DESC LIMIT 1");
if ($row = $res->fetchArray()) {
    $current_fundo = $row;
}
?>

<!-- Delete confirmation modal -->
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Confirm</h2>
            </div>
            <div class="modal-body">
                Do you really want to delete this background image?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <a class="btn btn-danger btn-ok">Delete</a>
            </div>
        </div>
    </div>
</div>

<div class="col-md-8 mx-auto">
    <div class="card-body">
        <div class="card bg-primary text-white">
            <div class="card-header card-header-warning">
                <center>
                    <h2><i class="fa fa-image"></i> Background Image Upload</h2>
                </center>
            </div>
            
            <div class="card-body">
                <?php if ($current_fundo): ?>
                <div class="text-center mb-4">
                    <h4>Current Background:</h4>
                    <img src="<?= $current_fundo['filepath'] ?>" class="img-fluid" style="max-height: 200px;">
                    <p class="mt-2">
                        <small>Uploaded: <?= date('Y-m-d H:i', strtotime($current_fundo['uploaded_at'])) ?></small>
                    </p>
                    <a href="#" class="btn btn-danger" data-href="./<?= $base_file ?>?delete=<?= $current_fundo['id'] ?>" data-toggle="modal" data-target="#confirm-delete">
                        <i class="fa fa-trash-o"></i> Delete Background
                    </a>
                </div>
                <hr>
                <?php endif; ?>
                
                <form method="post" enctype="multipart/form-data">
                    <div class="form-group">
                        <label class="form-label" for="fundo">Select Background Image</label>
                        <input type="file" class="form-control-file" id="fundo" name="fundo" accept="image/jpeg,image/png,image/gif" required>
                        <small class="form-text text-muted">
                            Only JPG, PNG, or GIF files are allowed (max size: <?= ini_get('upload_max_filesize') ?>)
                        </small>
                    </div>
                    <div class="form-group">
                        <center>
                            <button class="btn btn-info" name="submit" type="submit">
                                <i class="fa fa-upload"></i> Upload Background
                            </button>
                        </center>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include ('includes/studifooterolivecode.php'); ?>