<?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();

// Initialize variables
$message = '';
$messageType = '';
$editData = null;
$allJackpot = [];
$totalCount = 0;
$totalPages = 1;
$page = 1;

// Image upload handler
function handleImageUpload($editId = null) {
    $uploadDir = '../assets/uploads/jackpot/';
    
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    // If editing and no new file uploaded, keep existing image
    if ($editId && (!isset($_FILES['jackpot_image']) || $_FILES['jackpot_image']['error'] === UPLOAD_ERR_NO_FILE)) {
        $db = new Database();
        $existing = $db->getBuktiJackpotById($editId);
        return ['success' => true, 'path' => $existing['image_path']];
    }
    
    $imageType = $_POST['image_type'] ?? 'upload';
    
    if ($imageType === 'url') {
        $imageUrl = trim($_POST['image_url'] ?? '');
        if (empty($imageUrl)) {
            return ['success' => false, 'error' => 'URL gambar tidak boleh kosong!'];
        }
        
        // Validate URL
        if (!filter_var($imageUrl, FILTER_VALIDATE_URL)) {
            return ['success' => false, 'error' => 'URL gambar tidak valid!'];
        }
        
        return ['success' => true, 'path' => $imageUrl];
    } else {
        // File upload
        if (!isset($_FILES['jackpot_image']) || $_FILES['jackpot_image']['error'] !== UPLOAD_ERR_OK) {
            return ['success' => false, 'error' => 'Silakan pilih file gambar!'];
        }
        
        $file = $_FILES['jackpot_image'];
        $allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
        
        if (!in_array($file['type'], $allowedTypes)) {
            return ['success' => false, 'error' => 'Format file tidak didukung! Gunakan JPG, PNG, atau WEBP.'];
        }
        
        if ($file['size'] > 5 * 1024 * 1024) {
            return ['success' => false, 'error' => 'Ukuran file terlalu besar! Maksimal 5MB.'];
        }
        
        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        $fileName = 'jackpot_' . time() . '_' . uniqid() . '.' . $extension;
        $targetPath = $uploadDir . $fileName;
        
        if (move_uploaded_file($file['tmp_name'], $targetPath)) {
            return ['success' => true, 'path' => 'assets/uploads/jackpot/' . $fileName];
        } else {
            return ['success' => false, 'error' => 'Gagal mengupload file!'];
        }
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    try {
        switch ($_POST['action']) {
            case 'add':
                $imageResult = handleImageUpload();
                if ($imageResult['success']) {
                    $data = [
                        'title' => trim($_POST['title']),
                        'image_path' => $imageResult['path'],
                        'image_type' => $_POST['image_type'],
                        'jackpot_date' => $_POST['jackpot_date'],
                        'amount' => trim($_POST['amount']),
                        'description' => trim($_POST['description']),
                        'is_active' => isset($_POST['is_active']) ? 1 : 0
                    ];
                    
                    if ($db->addBuktiJackpot($data)) {
                        $message = 'Bukti jackpot berhasil ditambahkan!';
                        $messageType = 'success';
                    } else {
                        $message = 'Gagal menambahkan bukti jackpot!';
                        $messageType = 'error';
                    }
                } else {
                    $message = $imageResult['error'];
                    $messageType = 'error';
                }
                break;
                
            case 'edit':
                $imageResult = handleImageUpload($_POST['id']);
                if ($imageResult['success']) {
                    $data = [
                        'title' => trim($_POST['title']),
                        'image_path' => $imageResult['path'],
                        'image_type' => $_POST['image_type'],
                        'jackpot_date' => $_POST['jackpot_date'],
                        'amount' => trim($_POST['amount']),
                        'description' => trim($_POST['description']),
                        'is_active' => isset($_POST['is_active']) ? 1 : 0
                    ];
                    
                    if ($db->updateBuktiJackpot($_POST['id'], $data)) {
                        $message = 'Bukti jackpot berhasil diupdate!';
                        $messageType = 'success';
                    } else {
                        $message = 'Gagal mengupdate bukti jackpot!';
                        $messageType = 'error';
                    }
                } else {
                    $message = $imageResult['error'];
                    $messageType = 'error';
                }
                break;
                
            case 'delete':
                if ($db->deleteBuktiJackpot($_POST['id'])) {
                    $message = 'Bukti jackpot berhasil dihapus!';
                    $messageType = 'success';
                } else {
                    $message = 'Gagal menghapus bukti jackpot!';
                    $messageType = 'error';
                }
                break;
        }
    } catch (Exception $e) {
        $message = 'Error: ' . $e->getMessage();
        $messageType = 'error';
    }
}

// Pagination
$limit = 10;
$page = max(1, isset($_GET['page']) ? (int)$_GET['page'] : 1);
$offset = ($page - 1) * $limit;

// Get data
try {
    $totalCount = $db->getBuktiJackpotCount();
    $totalPages = ceil($totalCount / $limit);
    $allJackpot = $db->getBuktiJackpotPaginated($limit, $offset);
} catch (Exception $e) {
    $message = 'Error loading data: ' . $e->getMessage();
    $messageType = 'error';
}

// Get edit data if editing
if (isset($_GET['edit'])) {
    $editData = $db->getBuktiJackpotById((int)$_GET['edit']);
}

$pageTitle = 'Kelola Bukti Jackpot';
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; ?>

    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card bg-primary text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="card-title">Total Jackpot</h6>
                            <h3 class="mb-0"><?php echo $totalCount; ?></h3>
                        </div>
                        <div class="align-self-center">
                            <i class="bi bi-trophy fs-2"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-success text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="card-title">Active</h6>
                            <h3 class="mb-0"><?php echo $db->getBuktiJackpotCount('active'); ?></h3>
                        </div>
                        <div class="align-self-center">
                            <i class="bi bi-check-circle fs-2"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-warning text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="card-title">Inactive</h6>
                            <h3 class="mb-0"><?php echo $db->getBuktiJackpotCount('inactive'); ?></h3>
                        </div>
                        <div class="align-self-center">
                            <i class="bi bi-x-circle fs-2"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-info text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="card-title">This Month</h6>
                            <h3 class="mb-0"><?php echo $db->getBuktiJackpotCount('month'); ?></h3>
                        </div>
                        <div class="align-self-center">
                            <i class="bi bi-calendar-month fs-2"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add/Edit Form -->
    <div class="card mb-4">
        <div class="card-header">
            <h5 class="card-title mb-0">
                <i class="bi bi-<?php echo $editData ? 'pencil' : 'plus-circle'; ?>"></i>
                <?php echo $editData ? 'Edit Bukti Jackpot' : 'Tambah Bukti Jackpot'; ?>
            </h5>
        </div>
        <div class="card-body">
            <form method="POST" enctype="multipart/form-data">
                <?php if ($editData): ?>
                    <input type="hidden" name="action" value="edit">
                    <input type="hidden" name="id" value="<?php echo $editData['id']; ?>">
                <?php else: ?>
                    <input type="hidden" name="action" value="add">
                <?php endif; ?>
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label">Judul Jackpot <span class="text-danger">*</span></label>
                            <input type="text" name="title" class="form-control" required
                                   value="<?php echo $editData ? htmlspecialchars($editData['title']) : ''; ?>"
                                   placeholder="Contoh: Inatogel Jackpot Slot">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Tipe Gambar <span class="text-danger">*</span></label>
                            <div class="d-flex gap-3 mt-2">
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="image_type" id="upload" value="upload" 
                                           <?php echo (!$editData || $editData['image_type'] === 'upload') ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="upload">
                                        Upload File
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="image_type" id="url" value="url"
                                           <?php echo ($editData && $editData['image_type'] === 'url') ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="url">
                                        Link URL
                                    </label>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Upload Section -->
                        <div class="mb-3" id="upload-section">
                            <label class="form-label">Upload Gambar</label>
                            <input type="file" name="jackpot_image" class="form-control" accept="image/*">
                            <small class="form-text text-muted">Format: JPG, PNG, WebP. Maksimal 5MB.</small>
                        </div>
                        
                        <!-- URL Section -->
                        <div class="mb-3" id="url-section" style="display: none;">
                            <label class="form-label">Link URL Gambar</label>
                            <input type="url" name="image_url" class="form-control"
                                   value="<?php echo ($editData && $editData['image_type'] === 'url') ? htmlspecialchars($editData['image_path']) : ''; ?>"
                                   placeholder="https://example.com/image.jpg">
                        </div>
                        
                        <!-- Current Image Preview -->
                        <?php if ($editData && !empty($editData['image_path'])): ?>
                        <div class="mb-3">
                            <label class="form-label">Current Image:</label>
                            <div class="border rounded p-2">
                                <img src="<?php echo $editData['image_type'] === 'url' ? htmlspecialchars($editData['image_path']) : '../' . htmlspecialchars($editData['image_path']); ?>" 
                                     class="img-fluid rounded" style="max-height: 200px;">
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label">Tanggal Jackpot <span class="text-danger">*</span></label>
                            <input type="date" name="jackpot_date" class="form-control" required
                                   value="<?php echo $editData ? $editData['jackpot_date'] : date('Y-m-d'); ?>">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Jumlah Kemenangan <span class="text-danger">*</span></label>
                            <input type="text" name="amount" class="form-control" required
                                   value="<?php echo $editData ? htmlspecialchars($editData['amount']) : ''; ?>"
                                   placeholder="Contoh: Rp100,000,000">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Keterangan</label>
                            <textarea name="description" class="form-control" rows="4"
                                      placeholder="Deskripsi lengkap tentang kemenangan"><?php echo $editData ? htmlspecialchars($editData['description']) : ''; ?></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <div class="form-check">
                                <input type="checkbox" name="is_active" class="form-check-input" id="is_active"
                                       <?php echo (!$editData || $editData['is_active']) ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="is_active">
                                    Aktif (tampilkan di halaman utama)
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="d-flex justify-content-between">
                    <div>
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-check-circle"></i>
                            <?php echo $editData ? 'Update Bukti Jackpot' : 'Tambah Bukti Jackpot'; ?>
                        </button>
                        <?php if ($editData): ?>
                            <a href="bukti-jackpot.php" class="btn btn-secondary">
                                <i class="bi bi-x-circle"></i>
                                Cancel
                            </a>
                        <?php endif; ?>
                    </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>

    <!-- Data List -->
    <div class="card">
        <div class="card-header">
            <h5 class="card-title mb-0">
                <i class="bi bi-list-ul"></i>
                Daftar Bukti Jackpot (<?php echo $totalCount; ?>)
            </h5>
        </div>
        <div class="card-body p-0">
            <?php if (empty($allJackpot)): ?>
                <div class="text-center py-5">
                    <i class="bi bi-inbox fs-1 text-muted"></i>
                    <h5 class="mt-3 text-muted">Belum ada bukti jackpot</h5>
                    <p class="text-muted">Tambahkan bukti jackpot pertama Anda dengan mengisi form di atas.</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th width="60">#</th>
                                <th>Image</th>
                                <th>Title</th>
                                <th>Amount</th>
                                <th>Date</th>
                                <th>Status</th>
                                <th width="120">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($allJackpot as $index => $jackpot): ?>
                            <tr>
                                <td><?php echo $offset + $index + 1; ?></td>
                                <td>
                                    <img src="<?php echo $jackpot['image_type'] === 'url' ? htmlspecialchars($jackpot['image_path']) : '../' . htmlspecialchars($jackpot['image_path']); ?>" 
                                         class="rounded" style="width: 60px; height: 40px; object-fit: cover;">
                                </td>
                                <td>
                                    <div class="fw-bold"><?php echo htmlspecialchars($jackpot['title']); ?></div>
                                    <?php if (!empty($jackpot['description'])): ?>
                                    <small class="text-muted"><?php echo substr(htmlspecialchars($jackpot['description']), 0, 60); ?>...</small>
                                    <?php endif; ?>
                                </td>
                                <td class="fw-bold text-success"><?php echo htmlspecialchars($jackpot['amount']); ?></td>
                                <td><?php echo date('d/m/Y', strtotime($jackpot['jackpot_date'])); ?></td>
                                <td>
                                    <span class="badge bg-<?php echo $jackpot['is_active'] ? 'success' : 'secondary'; ?>">
                                        <?php echo $jackpot['is_active'] ? 'Active' : 'Inactive'; ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <a href="?edit=<?php echo $jackpot['id']; ?>" class="btn btn-outline-primary">
                                            <i class="bi bi-pencil"></i>
                                        </a>
                                        <button type="button" class="btn btn-outline-danger" 
                                                onclick="deleteJackpot(<?php echo $jackpot['id']; ?>)">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <!-- Pagination -->
                <?php if ($totalPages > 1): ?>
                <div class="d-flex justify-content-center mt-4">
                    <nav>
                        <ul class="pagination">
                            <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page - 1; ?>">Previous</a>
                                </li>
                            <?php endif; ?>
                            
                            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                </li>
                            <?php endfor; ?>
                            
                            <?php if ($page < $totalPages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page + 1; ?>">Next</a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
// Toggle image input sections
document.addEventListener('DOMContentLoaded', function() {
    const uploadRadio = document.getElementById('upload');
    const urlRadio = document.getElementById('url');
    const uploadSection = document.getElementById('upload-section');
    const urlSection = document.getElementById('url-section');
    
    function toggleSections() {
        if (uploadRadio.checked) {
            uploadSection.style.display = 'block';
            urlSection.style.display = 'none';
        } else {
            uploadSection.style.display = 'none';
            urlSection.style.display = 'block';
        }
    }
    
    uploadRadio.addEventListener('change', toggleSections);
    urlRadio.addEventListener('change', toggleSections);
    
    // Initial toggle
    toggleSections();
});

function deleteJackpot(id) {
    if (confirm('Apakah Anda yakin ingin menghapus bukti jackpot ini?')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="id" value="${id}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}
</script>

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

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

.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);
}

.table th {
    background-color: #f8f9fa;
    border-bottom: 2px solid #dee2e6;
    font-weight: 600;
}

.alert {
    border: none;
    border-radius: 10px;
}

.form-check-input:checked {
    background-color: #667eea;
    border-color: #667eea;
}

.page-link {
    color: #667eea;
}

.page-item.active .page-link {
    background-color: #667eea;
    border-color: #667eea;
}
</style>

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