<?php
session_start();
require_once 'config/config.php';
require_once 'auth/check_auth.php';

if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

$pageTitle = 'Photo Management System';
$currentPage = 'photo-management';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php echo $pageTitle; ?> | KSO Chandigarh</title>
    
    <!-- AdminLTE CSS -->
    <link rel="stylesheet" href="dist/css/adminlte.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <!-- Dropzone -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/dropzone.min.css">
    
    <style>
        .photo-stats {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .photo-gallery {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        
        .photo-item {
            position: relative;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
            transition: all 0.3s ease;
        }
        
        .photo-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        }
        
        .photo-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            cursor: pointer;
        }
        
        .photo-info {
            padding: 15px;
        }
        
        .photo-actions {
            position: absolute;
            top: 10px;
            right: 10px;
            display: none;
            gap: 5px;
        }
        
        .photo-item:hover .photo-actions {
            display: flex;
        }
        
        .photo-upload-zone {
            border: 2px dashed #dee2e6;
            border-radius: 10px;
            padding: 40px;
            text-align: center;
            background: #f8f9fa;
            margin-bottom: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .photo-upload-zone:hover {
            border-color: #007bff;
            background: #e7f3ff;
        }
        
        .photo-upload-zone.dragover {
            border-color: #007bff;
            background: #e7f3ff;
        }
        
        .album-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .album-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
        }
        
        .album-thumbnail {
            width: 100%;
            height: 150px;
            object-fit: cover;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        
        .filter-section {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .processing-queue {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .processing-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 10px;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .processing-item:last-child {
            border-bottom: none;
        }
        
        .photo-lightbox {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.9);
            z-index: 9999;
            justify-content: center;
            align-items: center;
        }
        
        .lightbox-content {
            max-width: 90%;
            max-height: 90%;
            position: relative;
        }
        
        .lightbox-image {
            max-width: 100%;
            max-height: 100%;
            border-radius: 8px;
        }
        
        .lightbox-close {
            position: absolute;
            top: 20px;
            right: 20px;
            color: white;
            font-size: 30px;
            cursor: pointer;
            z-index: 10000;
        }
        
        .bulk-actions {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            border: 1px solid #dee2e6;
            display: none;
        }
        
        .photo-checkbox {
            position: absolute;
            top: 10px;
            left: 10px;
            z-index: 10;
        }
        
        .approval-badge {
            position: absolute;
            top: 10px;
            left: 10px;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: bold;
        }
        
        .status-pending {
            background: #ffc107;
            color: #856404;
        }
        
        .status-approved {
            background: #28a745;
            color: white;
        }
        
        .status-rejected {
            background: #dc3545;
            color: white;
        }
    </style>
</head>

<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
    <!-- Include header -->
    <?php include 'templates/header.php'; ?>
    
    <!-- Include sidebar -->
    <?php include 'templates/sidebar.php'; ?>
    
    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <!-- Content Header -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0">
                            <i class="fas fa-camera text-primary"></i> Photo Management System
                        </h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                            <li class="breadcrumb-item active">Photo Management</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">
                
                <!-- Photo Statistics -->
                <div class="photo-stats">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-icon text-primary">
                                    <i class="fas fa-images"></i>
                                </div>
                                <h3 class="mb-1" id="totalPhotos">0</h3>
                                <p class="mb-0">Total Photos</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-icon text-success">
                                    <i class="fas fa-check-circle"></i>
                                </div>
                                <h3 class="mb-1" id="approvedPhotos">0</h3>
                                <p class="mb-0">Approved</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-icon text-warning">
                                    <i class="fas fa-clock"></i>
                                </div>
                                <h3 class="mb-1" id="pendingPhotos">0</h3>
                                <p class="mb-0">Pending Approval</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-icon text-info">
                                    <i class="fas fa-folder"></i>
                                </div>
                                <h3 class="mb-1" id="totalAlbums">0</h3>
                                <p class="mb-0">Albums</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Photo Upload Section -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-cloud-upload-alt"></i> Upload Photos
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="photo-upload-zone" id="photoUploadZone">
                            <i class="fas fa-cloud-upload-alt fa-3x text-muted mb-3"></i>
                            <h5>Drag & Drop Photos Here</h5>
                            <p class="text-muted">or click to select files</p>
                            <button class="btn btn-primary" onclick="selectFiles()">
                                <i class="fas fa-folder-open"></i> Select Files
                            </button>
                            <input type="file" id="photoFileInput" multiple accept="image/*" style="display: none;">
                        </div>
                        
                        <div class="row mt-3">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Album</label>
                                    <select class="form-control" id="uploadAlbum">
                                        <option value="">Select Album</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Tags</label>
                                    <input type="text" class="form-control" id="uploadTags" placeholder="Enter tags separated by commas">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Processing Queue -->
                <div class="processing-queue" id="processingQueue" style="display: none;">
                    <h6><i class="fas fa-cogs"></i> Processing Queue</h6>
                    <div id="processingItems">
                        <!-- Processing items will be shown here -->
                    </div>
                </div>

                <!-- Filters -->
                <div class="filter-section">
                    <h5 class="mb-3"><i class="fas fa-filter"></i> Filter Photos</h5>
                    <div class="row">
                        <div class="col-md-3">
                            <select class="form-control" id="albumFilter">
                                <option value="">All Albums</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select class="form-control" id="statusFilter">
                                <option value="">All Status</option>
                                <option value="pending">Pending</option>
                                <option value="approved">Approved</option>
                                <option value="rejected">Rejected</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <input type="text" class="form-control" id="searchFilter" placeholder="Search photos...">
                        </div>
                        <div class="col-md-2">
                            <button class="btn btn-primary btn-block" onclick="filterPhotos()">
                                <i class="fas fa-search"></i> Filter
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Bulk Actions -->
                <div class="bulk-actions" id="bulkActions">
                    <div class="row">
                        <div class="col-md-6">
                            <span class="text-muted">
                                <span id="selectedCount">0</span> photos selected
                            </span>
                        </div>
                        <div class="col-md-6 text-right">
                            <button class="btn btn-success btn-sm" onclick="bulkApprove()">
                                <i class="fas fa-check"></i> Approve
                            </button>
                            <button class="btn btn-warning btn-sm" onclick="bulkReject()">
                                <i class="fas fa-times"></i> Reject
                            </button>
                            <button class="btn btn-danger btn-sm" onclick="bulkDelete()">
                                <i class="fas fa-trash"></i> Delete
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Photo Gallery -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-images"></i> Photo Gallery
                        </h3>
                        <div class="card-tools">
                            <button class="btn btn-primary btn-sm" onclick="createAlbum()">
                                <i class="fas fa-plus"></i> Create Album
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="photo-gallery" id="photoGallery">
                            <!-- Photos will be loaded here -->
                        </div>
                    </div>
                </div>

            </div>
        </section>
    </div>
</div>

<!-- Photo Lightbox -->
<div class="photo-lightbox" id="photoLightbox">
    <div class="lightbox-close" onclick="closeLightbox()">×</div>
    <div class="lightbox-content">
        <img class="lightbox-image" id="lightboxImage" src="" alt="">
    </div>
</div>

<!-- Include footer -->
<?php include 'templates/footer.php'; ?>

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="dist/js/adminlte.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/dropzone.min.js"></script>

<script>
// Industrial-Level Photo Management System
$(document).ready(function() {
    loadPhotos();
    loadStatistics();
    loadAlbums();
    setupFileUpload();
    setupBulkActions();
});

let selectedPhotos = [];

function loadPhotos() {
    const filters = {
        album: $('#albumFilter').val(),
        status: $('#statusFilter').val(),
        search: $('#searchFilter').val()
    };
    
    $.ajax({
        url: 'api/photos/fetch.php',
        method: 'GET',
        data: filters,
        success: function(response) {
            if (response.success) {
                const gallery = $('#photoGallery');
                gallery.empty();
                
                response.photos.forEach(function(photo) {
                    gallery.append(createPhotoItem(photo));
                });
            }
        },
        error: function() {
            if (window.ksoToast) {
                window.ksoToast.error('Error loading photos');
            }
        }
    });
}

function createPhotoItem(photo) {
    const statusClass = `status-${photo.status}`;
    
    return `
        <div class="photo-item">
            <input type="checkbox" class="photo-checkbox" value="${photo.id}">
            <div class="approval-badge ${statusClass}">${photo.status}</div>
            <img class="photo-image" src="${photo.thumbnail_url}" alt="${photo.filename}" onclick="openLightbox('${photo.url}')">
            <div class="photo-actions">
                <button class="btn btn-sm btn-success" onclick="approvePhoto(${photo.id})" title="Approve">
                    <i class="fas fa-check"></i>
                </button>
                <button class="btn btn-sm btn-warning" onclick="rejectPhoto(${photo.id})" title="Reject">
                    <i class="fas fa-times"></i>
                </button>
                <button class="btn btn-sm btn-danger" onclick="deletePhoto(${photo.id})" title="Delete">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
            <div class="photo-info">
                <h6>${photo.filename}</h6>
                <p class="text-muted mb-1">Album: ${photo.album_name || 'None'}</p>
                <p class="text-muted mb-0">Uploaded: ${formatDate(photo.uploaded_at)}</p>
            </div>
        </div>
    `;
}

function setupFileUpload() {
    const uploadZone = $('#photoUploadZone');
    const fileInput = $('#photoFileInput');
    
    uploadZone.on('click', function() {
        fileInput.click();
    });
    
    fileInput.on('change', function() {
        const files = this.files;
        if (files.length > 0) {
            uploadFiles(files);
        }
    });
    
    // Drag and drop functionality
    uploadZone.on('dragover', function(e) {
        e.preventDefault();
        $(this).addClass('dragover');
    });
    
    uploadZone.on('dragleave', function(e) {
        e.preventDefault();
        $(this).removeClass('dragover');
    });
    
    uploadZone.on('drop', function(e) {
        e.preventDefault();
        $(this).removeClass('dragover');
        
        const files = e.originalEvent.dataTransfer.files;
        if (files.length > 0) {
            uploadFiles(files);
        }
    });
}

function uploadFiles(files) {
    const formData = new FormData();
    const album = $('#uploadAlbum').val();
    const tags = $('#uploadTags').val();
    
    for (let i = 0; i < files.length; i++) {
        formData.append('photos[]', files[i]);
    }
    
    formData.append('album', album);
    formData.append('tags', tags);
    
    // Show processing queue
    $('#processingQueue').show();
    
    $.ajax({
        url: 'api/photos/upload.php',
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success(`${response.uploaded_count} photos uploaded successfully!`);
                }
                loadPhotos();
                loadStatistics();
                $('#processingQueue').hide();
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Upload failed: ' + response.message);
                }
            }
        },
        error: function() {
            if (window.ksoToast) {
                window.ksoToast.error('Upload failed');
            }
            $('#processingQueue').hide();
        }
    });
}

function setupBulkActions() {
    $(document).on('change', '.photo-checkbox', function() {
        updateSelectedPhotos();
    });
}

function updateSelectedPhotos() {
    selectedPhotos = [];
    $('.photo-checkbox:checked').each(function() {
        selectedPhotos.push($(this).val());
    });
    
    $('#selectedCount').text(selectedPhotos.length);
    $('#bulkActions').toggle(selectedPhotos.length > 0);
}

function approvePhoto(id) {
    updatePhotoStatus(id, 'approved');
}

function rejectPhoto(id) {
    updatePhotoStatus(id, 'rejected');
}

function updatePhotoStatus(id, status) {
    $.ajax({
        url: 'api/photos/update-status.php',
        method: 'POST',
        data: { id: id, status: status },
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success(`Photo ${status} successfully!`);
                }
                loadPhotos();
                loadStatistics();
            }
        }
    });
}

function deletePhoto(id) {
    if (confirm('Are you sure you want to delete this photo?')) {
        $.ajax({
            url: 'api/photos/delete.php',
            method: 'POST',
            data: { id: id },
            success: function(response) {
                if (response.success) {
                    if (window.ksoToast) {
                        window.ksoToast.success('Photo deleted successfully!');
                    }
                    loadPhotos();
                    loadStatistics();
                }
            }
        });
    }
}

function openLightbox(imageUrl) {
    $('#lightboxImage').attr('src', imageUrl);
    $('#photoLightbox').css('display', 'flex');
}

function closeLightbox() {
    $('#photoLightbox').hide();
}

function loadStatistics() {
    $.ajax({
        url: 'api/photos/stats.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                $('#totalPhotos').text(response.stats.total);
                $('#approvedPhotos').text(response.stats.approved);
                $('#pendingPhotos').text(response.stats.pending);
                $('#totalAlbums').text(response.stats.albums);
            }
        }
    });
}

function loadAlbums() {
    $.ajax({
        url: 'api/photos/albums.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const albumSelect = $('#uploadAlbum, #albumFilter');
                albumSelect.find('option:not(:first)').remove();
                
                response.albums.forEach(function(album) {
                    albumSelect.append(`<option value="${album.id}">${album.name}</option>`);
                });
            }
        }
    });
}

function filterPhotos() {
    loadPhotos();
}

function bulkApprove() {
    if (selectedPhotos.length === 0) return;
    
    $.ajax({
        url: 'api/photos/bulk-approve.php',
        method: 'POST',
        data: { ids: selectedPhotos },
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('Photos approved successfully!');
                }
                loadPhotos();
                loadStatistics();
            }
        }
    });
}

function bulkReject() {
    if (selectedPhotos.length === 0) return;
    
    $.ajax({
        url: 'api/photos/bulk-reject.php',
        method: 'POST',
        data: { ids: selectedPhotos },
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('Photos rejected successfully!');
                }
                loadPhotos();
                loadStatistics();
            }
        }
    });
}

function bulkDelete() {
    if (selectedPhotos.length === 0) return;
    
    if (confirm(`Are you sure you want to delete ${selectedPhotos.length} photos?`)) {
        $.ajax({
            url: 'api/photos/bulk-delete.php',
            method: 'POST',
            data: { ids: selectedPhotos },
            success: function(response) {
                if (response.success) {
                    if (window.ksoToast) {
                        window.ksoToast.success('Photos deleted successfully!');
                    }
                    loadPhotos();
                    loadStatistics();
                }
            }
        });
    }
}

function createAlbum() {
    if (window.ksoToast) {
        window.ksoToast.info('Album creation feature coming soon!');
    }
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
    });
}
</script>

</body>
</html>
