<?php
define('ADMIN_ACCESS', true);
require_once 'config.php';
require_once '../includes/database.php';
require_once '../includes/site-manager.php';
require_once '../includes/multi-tenant-auth.php';
require_once '../includes/integrated-admin-auth.php';
require_once '../includes/permission-middleware.php';

// Check integrated authentication
$integratedAuth = new IntegratedAdminAuth();
if (!isset($_SESSION['integrated_admin_session_id'])) {
    header('Location: login.php');
    exit;
}

$adminData = $integratedAuth->validateSession($_SESSION['integrated_admin_session_id']);
if (!$adminData) {
    session_destroy();
    header('Location: login.php');
    exit;
}

// Update session data
$_SESSION['admin_data'] = $adminData;

// CRITICAL: Set current site ID for proper data isolation
$_SESSION['current_site_id'] = $adminData['site_id'] ?? 1;

$db = new Database();
$message = '';
$messageType = '';

// Handle banner uploads and updates
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_banners') {
    try {
        $bannerUpdates = [];
        $uploadErrors = [];
        
        // Process 5 banners
        for ($i = 1; $i <= 5; $i++) {
            $debugLog .= "--- Processing Banner $i ---\n";
            
            // Handle image upload
            if (isset($_FILES["banner_{$i}_image"]) && $_FILES["banner_{$i}_image"]['error'] === UPLOAD_ERR_OK) {
                $debugLog .= "Banner $i: File upload detected\n";
                
                $uploadDir = '../assets/banners/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                    $debugLog .= "Banner $i: Created upload directory\n";
                }
                
                $fileName = 'banner_' . $i . '_' . time() . '.' . pathinfo($_FILES["banner_{$i}_image"]['name'], PATHINFO_EXTENSION);
                $uploadPath = $uploadDir . $fileName;
                $debugLog .= "Banner $i: Target path: $uploadPath\n";
                
                if (move_uploaded_file($_FILES["banner_{$i}_image"]['tmp_name'], $uploadPath)) {
                    $debugLog .= "Banner $i: ✅ File moved successfully\n";
                    $bannerUpdates[] = ['key' => "banner_{$i}_image", 'value' => "assets/banners/" . $fileName];
                    $debugLog .= "Banner $i: Added to database update queue\n";
                } else {
                    $debugLog .= "Banner $i: ❌ File move FAILED\n";
                    $uploadErrors[] = "Gagal upload banner $i";
                }
            } else if (isset($_FILES["banner_{$i}_image"])) {
                $error = $_FILES["banner_{$i}_image"]['error'];
                $debugLog .= "Banner $i: Upload error code: $error\n";
                if ($error === UPLOAD_ERR_NO_FILE) {
                    $debugLog .= "Banner $i: No file selected\n";
                }
            }
            
            // Handle link update
            $linkValue = trim($_POST["banner_{$i}_link"] ?? '');
            if (!empty($linkValue)) {
                $debugLog .= "Banner $i: Link update: $linkValue\n";
                $bannerUpdates[] = ['key' => "banner_{$i}_link", 'value' => $linkValue];
            }
        }
        
        $debugLog .= "Total updates to process: " . count($bannerUpdates) . "\n";
        
        // Update database
        foreach ($bannerUpdates as $update) {
            $debugLog .= "Updating: {$update['key']} = {$update['value']}\n";
            $result = $db->updateWebsiteSetting($update['key'], $update['value']);
            $debugLog .= "Database update result: " . ($result ? 'SUCCESS' : 'FAILED') . "\n";
        }
        
        if (empty($uploadErrors)) {
            $message = 'Banner berhasil diupdate!';
            $messageType = 'success';
            $debugLog .= "Final result: SUCCESS - No upload errors\n";
        } else {
            $message = 'Ada error saat mengupdate banner: ' . implode(', ', $uploadErrors);
            $messageType = 'error';
            $debugLog .= "Final result: ERROR - " . implode(', ', $uploadErrors) . "\n";
        }
        
    } catch (Exception $e) {
        $message = 'Error: ' . $e->getMessage();
        $messageType = 'error';
        $debugLog .= "EXCEPTION: " . $e->getMessage() . "\n";
    }
    
    // Save debug log
    $debugLog .= "=== END DEBUG ===\n";
    file_put_contents('../banner_upload_debug.log', $debugLog, FILE_APPEND);
}

// Get current banner settings
$bannerSettings = [];
for ($i = 1; $i <= 5; $i++) {
    $bannerSettings["banner_{$i}_image"] = $db->getWebsiteSetting("banner_{$i}_image") ?: '';
    $bannerSettings["banner_{$i}_link"] = $db->getWebsiteSetting("banner_{$i}_link") ?: '';
}

$pageTitle = 'Banner Management';
include 'admin-sidebar-template.php';
?>

<div class="content-body">
    <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType === 'success' ? 'success' : 'danger'; ?> alert-dismissible fade show">
            <i class="bi bi-<?php echo $messageType === 'success' ? 'check-circle' : 'exclamation-triangle'; ?>"></i>
            <?php echo htmlspecialchars($message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="card">
        <div class="card-header">
            <h5 class="card-title mb-0">
                <i class="bi bi-image"></i>
                Kelola Banner Slider
            </h5>
        </div>
        <div class="card-body">
            <p class="text-muted mb-4">
                Kelola banner slider yang ditampilkan di halaman utama website. Anda dapat mengupload hingga 5 banner.
            </p>
            
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="update_banners">
                
                <div class="row">
                    <?php for ($i = 1; $i <= 5; $i++): ?>
                    <div class="col-md-6 mb-4">
                        <div class="card">
                            <div class="card-header">
                                <h6 class="mb-0">Banner <?php echo $i; ?></h6>
                            </div>
                            <div class="card-body">
                                <!-- Current Image -->
                                <?php if (!empty($bannerSettings["banner_{$i}_image"])): ?>
                                <div class="mb-3">
                                    <label class="form-label">Current Image:</label>
                                    <div class="border rounded p-2">
                                        <img src="../<?php echo htmlspecialchars($bannerSettings["banner_{$i}_image"]); ?>" 
                                             class="img-fluid rounded" style="max-height: 200px;">
                                    </div>
                                </div>
                                <?php endif; ?>
                                
                                <!-- Upload New Image -->
                                <div class="mb-3">
                                    <label for="banner_<?php echo $i; ?>_image" class="form-label">
                                        <?php echo !empty($bannerSettings["banner_{$i}_image"]) ? 'Ganti Gambar' : 'Upload Gambar'; ?>
                                    </label>
                                    <input type="file" class="form-control" 
                                           id="banner_<?php echo $i; ?>_image" 
                                           name="banner_<?php echo $i; ?>_image"
                                           accept="image/*">
                                    <small class="form-text text-muted">
                                        Format: JPG, PNG, WEBP. Ukuran maksimal: 2MB. Resolusi yang disarankan: 1200x400px
                                    </small>
                                </div>
                                
                                <!-- Link -->
                                <div class="mb-3">
                                    <label for="banner_<?php echo $i; ?>_link" class="form-label">Link (Opsional)</label>
                                    <input type="url" class="form-control" 
                                           id="banner_<?php echo $i; ?>_link" 
                                           name="banner_<?php echo $i; ?>_link"
                                           value="<?php echo htmlspecialchars($bannerSettings["banner_{$i}_link"]); ?>"
                                           placeholder="https://example.com">
                                    <small class="form-text text-muted">
                                        URL tujuan ketika banner diklik (kosongkan jika tidak perlu link)
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endfor; ?>
                </div>
                
                <div class="d-flex justify-content-between">
                    <div>
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-check-circle"></i>
                            Update Banner
                        </button>
                        <a href="dashboard.php" class="btn btn-secondary">
                            <i class="bi bi-arrow-left"></i>
                            Kembali
                        </a>
                    </div>
                    <div>
                        <a href="../" target="_blank" class="btn btn-outline-info">
                            <i class="bi bi-eye"></i>
                            Preview Website
                        </a>
                    </div>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Banner Guidelines -->
    <div class="card mt-4">
        <div class="card-header">
            <h6 class="mb-0">
                <i class="bi bi-info-circle"></i>
                Panduan Banner
            </h6>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <h6>Spesifikasi Gambar:</h6>
                    <ul class="list-unstyled">
                        <li><i class="bi bi-check text-success"></i> Resolusi: 1200x400px (optimal)</li>
                        <li><i class="bi bi-check text-success"></i> Format: JPG, PNG, WEBP</li>
                        <li><i class="bi bi-check text-success"></i> Ukuran: Maksimal 2MB</li>
                        <li><i class="bi bi-check text-success"></i> Ratio: 3:1 (landscape)</li>
                    </ul>
                </div>
                <div class="col-md-6">
                    <h6>Tips:</h6>
                    <ul class="list-unstyled">
                        <li><i class="bi bi-lightbulb text-warning"></i> Gunakan gambar dengan kualitas tinggi</li>
                        <li><i class="bi bi-lightbulb text-warning"></i> Pastikan teks di banner mudah dibaca</li>
                        <li><i class="bi bi-lightbulb text-warning"></i> Gunakan warna yang kontras</li>
                        <li><i class="bi bi-lightbulb text-warning"></i> Banner akan ditampilkan secara bergantian</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.card {
    border: none;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.card-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-bottom: none;
}

.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
}

.btn-primary:hover {
    background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
    transform: translateY(-1px);
}

.form-control:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
}

.alert {
    border: none;
    border-radius: 10px;
}
</style>

<?php include 'admin-sidebar-footer.php'; ?>