<?php
// Database connection
$db = new SQLite3('./api/.db.db');

// Table name
$table_name = "logo_studiolivecode";

// 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['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['logo'];
        
        // 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.');
        }
        
        // Validate file extension
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, ['jpg', 'jpeg', 'png', 'gif'])) {
            die('Error: Invalid file extension.');
        }
        
        // Definir nome fixo como logo.extensão
        $filename = 'logo.' . $ext;
        $filepath = $upload_dir . $filename;
        
        // Delete old logo if exists (independente da extensão)
        $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 logo.png/logo.jpg/etc in the directory
        $existing_logos = glob($upload_dir . 'logo.*');
        foreach ($existing_logos as $existing_logo) {
            if (file_exists($existing_logo)) {
                unlink($existing_logo);
            }
        }
        
        // Move uploaded file
        if (move_uploaded_file($file['tmp_name'], $filepath)) {
            // 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: Failed to move uploaded file.');
        }
    } else {
        die('Error: No file uploaded or upload error.');
    }
}

// Delete logo
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 logo
$current_logo = null;
$res = $db->query("SELECT * FROM {$table_name} ORDER BY uploaded_at DESC LIMIT 1");
if ($row = $res->fetchArray()) {
    $current_logo = $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 logo?
            </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> Logo Upload</h2>
                </center>
            </div>
            
            <div class="card-body">
                <?php if ($current_logo): ?>
                <div class="text-center mb-4">
                    <h4>Current Logo:</h4>
                    <img src="<?= $current_logo['filepath'] ?>" class="img-fluid" style="max-height: 200px;">
                    <p class="mt-2">
                        <small>Uploaded: <?= date('Y-m-d H:i', strtotime($current_logo['uploaded_at'])) ?></small>
                    </p>
                    <a href="#" class="btn btn-danger" data-href="./<?= $base_file ?>?delete=<?= $current_logo['id'] ?>" data-toggle="modal" data-target="#confirm-delete">
                        <i class="fa fa-trash-o"></i> Delete Logo
                    </a>
                </div>
                <hr>
                <?php endif; ?>
                
                <form method="post" enctype="multipart/form-data">
                    <div class="form-group">
                        <label class="form-label" for="logo">Select Logo Image</label>
                        <input type="file" class="form-control-file" id="logo" name="logo" 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 Logo
                            </button>
                        </center>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include ('includes/studifooterolivecode.php'); ?>