<?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';
include 'deploy_update.php';

// Check if admin
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    header('Location: login.php');
    exit();
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $version = $_POST['version'] ?? '';
    
    try {
        $deployer = new UpdateDeployer($version);
        
        switch ($action) {
            case 'create':
                $deployer->createUpdatePackage();
                $_SESSION['success'] = "Update package structure created for version $version";
                break;
                
            case 'build':
                if (!empty($_FILES['files']) || !empty($_FILES['migrations'])) {
                    // Handle file uploads
                    $tempDir = dirname(__FILE__) . '/temp/' . $version;
                    
                    // Handle updated files
                    if (!empty($_FILES['files']['name'][0])) {
                        $filesDir = $tempDir . '/files';
                        foreach ($_FILES['files']['tmp_name'] as $index => $tmpName) {
                            $fileName = $_FILES['files']['name'][$index];
                            move_uploaded_file($tmpName, $filesDir . '/' . $fileName);
                        }
                    }
                    
                    // Handle migrations
                    if (!empty($_FILES['migrations']['name'][0])) {
                        $migrationsDir = $tempDir . '/migrations';
                        foreach ($_FILES['migrations']['tmp_name'] as $index => $tmpName) {
                            $fileName = $_FILES['migrations']['name'][$index];
                            move_uploaded_file($tmpName, $migrationsDir . '/' . $fileName);
                        }
                    }
                    
                    // Handle changelog
                    if (!empty($_POST['changelog'])) {
                        file_put_contents($tempDir . '/changelog.txt', $_POST['changelog']);
                    }
                    
                    // Handle requirements
                    if (!empty($_POST['requirements'])) {
                        file_put_contents($tempDir . '/requirements.txt', $_POST['requirements']);
                    }
                }
                
                $packageInfo = $deployer->buildPackage();
                $_SESSION['success'] = "Update package built successfully. Checksum: " . $packageInfo['checksum'];
                break;
                
            case 'publish':
                $packageInfo = $deployer->buildPackage();
                $deployer->publishPackage($packageInfo);
                $_SESSION['success'] = "Update package published successfully";
                break;
                
            case 'verify':
                if ($deployer->verifyPackage()) {
                    $_SESSION['success'] = "Package verification successful";
                }
                break;
        }
    } catch (Exception $e) {
        $_SESSION['error'] = $e->getMessage();
    }
    
    header('Location: manage_updates.php');
    exit();
}

// Get list of update packages
$packagesDir = dirname(__FILE__) . '/packages';
$packages = [];
if (file_exists($packagesDir)) {
    $files = glob($packagesDir . '/update_*.zip');
    foreach ($files as $file) {
        $version = str_replace(['update_', '.zip'], '', basename($file));
        $packages[] = [
            'version' => $version,
            'size' => filesize($file),
            'modified' => filemtime($file),
            'checksum' => md5_file($file)
        ];
    }
}

// Sort packages by version number
usort($packages, function($a, $b) {
    return version_compare($b['version'], $a['version']);
});
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Manage Updates')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/dropzone/dropzone.css" rel="stylesheet">
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'System', 'title' => 'Manage Updates')); ?>

                    <div class="row">
                        <div class="col-xl-12">
                            <?php if (isset($_SESSION['success'])): ?>
                                <div class="alert alert-success alert-dismissible fade show" role="alert">
                                    <?php 
                                    echo $_SESSION['success'];
                                    unset($_SESSION['success']);
                                    ?>
                                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                </div>
                            <?php endif; ?>

                            <?php if (isset($_SESSION['error'])): ?>
                                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                    <?php 
                                    echo $_SESSION['error'];
                                    unset($_SESSION['error']);
                                    ?>
                                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                </div>
                            <?php endif; ?>

                            <!-- Create New Update -->
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Create New Update</h4>
                                </div>
                                <div class="card-body">
                                    <form action="" method="post" class="row g-3">
                                        <input type="hidden" name="action" value="create">
                                        
                                        <div class="col-md-6">
                                            <label class="form-label">Version Number</label>
                                            <input type="text" class="form-control" name="version" 
                                                   placeholder="e.g., 1.2.0" required>
                                        </div>
                                        
                                        <div class="col-12">
                                            <button type="submit" class="btn btn-primary">
                                                Create Update Package
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>

                            <!-- Build Update -->
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Build Update Package</h4>
                                </div>
                                <div class="card-body">
                                    <form action="" method="post" enctype="multipart/form-data" class="row g-3">
                                        <input type="hidden" name="action" value="build">
                                        
                                        <div class="col-md-6">
                                            <label class="form-label">Version Number</label>
                                            <input type="text" class="form-control" name="version" 
                                                   placeholder="e.g., 1.2.0" required>
                                        </div>
                                        
                                        <div class="col-md-12">
                                            <label class="form-label">Updated Files</label>
                                            <input type="file" class="form-control" name="files[]" multiple>
                                            <small class="text-muted">Select all files that need to be updated</small>
                                        </div>
                                        
                                        <div class="col-md-12">
                                            <label class="form-label">Database Migrations</label>
                                            <input type="file" class="form-control" name="migrations[]" multiple>
                                            <small class="text-muted">Select SQL migration files if any</small>
                                        </div>
                                        
                                        <div class="col-md-12">
                                            <label class="form-label">Changelog</label>
                                            <textarea class="form-control" name="changelog" rows="4" required></textarea>
                                        </div>
                                        
                                        <div class="col-md-12">
                                            <label class="form-label">Requirements</label>
                                            <textarea class="form-control" name="requirements" rows="2"></textarea>
                                            <small class="text-muted">e.g., PHP 7.4+, MySQL 5.7+</small>
                                        </div>
                                        
                                        <div class="col-12">
                                            <button type="submit" class="btn btn-primary">
                                                Build Package
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>

                            <!-- Update Packages -->
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Update Packages</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Version</th>
                                                    <th>Size</th>
                                                    <th>Modified</th>
                                                    <th>Checksum</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($packages as $package): ?>
                                                <tr>
                                                    <td><?php echo $package['version']; ?></td>
                                                    <td><?php echo formatBytes($package['size']); ?></td>
                                                    <td><?php echo date('Y-m-d H:i', $package['modified']); ?></td>
                                                    <td>
                                                        <span class="small text-muted"><?php echo $package['checksum']; ?></span>
                                                    </td>
                                                    <td>
                                                        <form action="" method="post" class="d-inline">
                                                            <input type="hidden" name="action" value="verify">
                                                            <input type="hidden" name="version" value="<?php echo $package['version']; ?>">
                                                            <button type="submit" class="btn btn-sm btn-info">
                                                                Verify
                                                            </button>
                                                        </form>
                                                        
                                                        <form action="" method="post" class="d-inline">
                                                            <input type="hidden" name="action" value="publish">
                                                            <input type="hidden" name="version" value="<?php echo $package['version']; ?>">
                                                            <button type="submit" class="btn btn-sm btn-success">
                                                                Publish
                                                            </button>
                                                        </form>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                                
                                                <?php if (empty($packages)): ?>
                                                <tr>
                                                    <td colspan="5" class="text-center">No update packages found</td>
                                                </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/dropzone/dropzone.min.js"></script>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Confirm package build
        document.querySelectorAll('form[action="build"]').forEach(form => {
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                
                Swal.fire({
                    title: 'Build Update Package',
                    text: 'Are you sure you want to build this update package?',
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, Build It',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        form.submit();
                    }
                });
            });
        });

        // Confirm package publish
        document.querySelectorAll('form[action="publish"]').forEach(form => {
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                
                Swal.fire({
                    title: 'Publish Update Package',
                    text: 'This will make the update available to all users. Continue?',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, Publish It',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        form.submit();
                    }
                });
            });
        });
    });

    function formatBytes(bytes) {
        const units = ['B', 'KB', 'MB', 'GB'];
        let size = bytes;
        let unitIndex = 0;
        
        while (size >= 1024 && unitIndex < units.length - 1) {
            size /= 1024;
            unitIndex++;
        }
        
        return `${size.toFixed(2)} ${units[unitIndex]}`;
    }
    </script>
</body>
</html>