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

// Check if user is logged in and has appropriate permissions
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

$pageTitle = 'Document Management';
$currentPage = 'documents';
?>

<!-- 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">Documents Management</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                        <li class="breadcrumb-item active">Documents</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <!-- Info boxes -->
            <div class="row">
                <div class="col-12 col-sm-6 col-md-3">
                    <div class="info-box">
                        <span class="info-box-icon bg-info elevation-1"><i class="fas fa-file-alt"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Total Documents</span>
                            <span class="info-box-number" id="totalDocuments">0</span>
                        </div>
                    </div>
                </div>
                <div class="col-12 col-sm-6 col-md-3">
                    <div class="info-box mb-3">
                        <span class="info-box-icon bg-success elevation-1"><i class="fas fa-eye"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Public Documents</span>
                            <span class="info-box-number" id="publicDocuments">0</span>
                        </div>
                    </div>
                </div>
                <div class="col-12 col-sm-6 col-md-3">
                    <div class="info-box mb-3">
                        <span class="info-box-icon bg-warning elevation-1"><i class="fas fa-lock"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Private Documents</span>
                            <span class="info-box-number" id="privateDocuments">0</span>
                        </div>
                    </div>
                </div>
                <div class="col-12 col-sm-6 col-md-3">
                    <div class="info-box mb-3">
                        <span class="info-box-icon bg-danger elevation-1"><i class="fas fa-download"></i></span>
                        <div class="info-box-content">
                            <span class="info-box-text">Total Downloads</span>
                            <span class="info-box-number" id="totalDownloads">0</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Documents Table -->
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">All Documents</h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#uploadDocumentModal">
                                    <i class="fas fa-upload"></i> Upload Document
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <table id="documentsTable" class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th>Title</th>
                                        <th>Category</th>
                                        <th>File Type</th>
                                        <th>File Size</th>
                                        <th>Visibility</th>
                                        <th>Downloads</th>
                                        <th>Uploaded</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Data will be populated via AJAX -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- Upload Document Modal -->
<div class="modal fade" id="uploadDocumentModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Upload New Document</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form id="uploadDocumentForm" enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="form-group">
                        <label>Document Title *</label>
                        <input type="text" class="form-control" name="title" required>
                    </div>
                    <div class="form-group">
                        <label>Description</label>
                        <textarea class="form-control" name="description" rows="3"></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Category *</label>
                                <select class="form-control" name="category" required>
                                    <option value="">Select Category</option>
                                    <option value="general">General</option>
                                    <option value="financial">Financial</option>
                                    <option value="membership">Membership</option>
                                    <option value="events">Events</option>
                                    <option value="policies">Policies</option>
                                    <option value="other">Other</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Visibility *</label>
                                <select class="form-control" name="is_public" required>
                                    <option value="">Select Visibility</option>
                                    <option value="1">Public</option>
                                    <option value="0">Private</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Document File *</label>
                        <div class="input-group">
                            <div class="custom-file">
                                <input type="file" class="custom-file-input" name="document_file" required 
                                       accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt">
                                <label class="custom-file-label" for="document_file">Choose file</label>
                            </div>
                        </div>
                        <small class="form-text text-muted">Allowed formats: PDF, DOC, DOCX, XLS, XLSX, PPT, PPTX, TXT (Max: 10MB)</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Upload Document</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Load document statistics
    loadDocumentStats();
    
    // Initialize DataTable
    const table = $('#documentsTable').DataTable({
        "processing": true,
        "serverSide": false,
        "ajax": {
            "url": "api/fetch_documents.php",
            "dataSrc": function(json) {
                return json.success ? json.data : [];
            }
        },
        "columns": [
            { "data": "title" },
            { "data": "category" },
            { "data": "file_type" },
            { "data": "file_size", "render": function(data) {
                return formatFileSize(data);
            }},
            { "data": "is_public", "render": function(data) {
                return data == 1 ? '<span class="badge badge-success">Public</span>' : '<span class="badge badge-warning">Private</span>';
            }},
            { "data": "download_count" },
            { "data": "created_at", "render": function(data) {
                return new Date(data).toLocaleDateString();
            }},
            { "data": null, "render": function(data) {
                return `
                    <button class="btn btn-sm btn-info" onclick="viewDocument(${data.id})">View</button>
                    <button class="btn btn-sm btn-success" onclick="downloadDocument(${data.id})">Download</button>
                    <button class="btn btn-sm btn-danger" onclick="deleteDocument(${data.id})">Delete</button>
                `;
            }}
        ]
    });

    // Upload document form submission
    $('#uploadDocumentForm').on('submit', function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        
        $.ajax({
            url: 'api/upload_document.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    $('#uploadDocumentModal').modal('hide');
                    table.ajax.reload();
                    loadDocumentStats();
                    toastr.success('Document uploaded successfully');
                } else {
                    toastr.error(response.message);
                }
            },
            error: function() {
                toastr.error('Error uploading document');
            }
        });
    });

    // Custom file input label update
    $('.custom-file-input').on('change', function() {
        let fileName = $(this).val().split('\\').pop();
        $(this).siblings('.custom-file-label').addClass('selected').html(fileName);
    });
});

function loadDocumentStats() {
    $.get('api/fetch_document_stats.php', function(data) {
        if (data.success) {
            $('#totalDocuments').text(data.data.total);
            $('#publicDocuments').text(data.data.public);
            $('#privateDocuments').text(data.data.private);
            $('#totalDownloads').text(data.data.total_downloads);
        }
    });
}

function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function viewDocument(id) {
    window.open(`api/view_document.php?id=${id}`, '_blank');
}

function downloadDocument(id) {
    window.location.href = `api/download_document.php?id=${id}`;
}

function deleteDocument(id) {
    if (confirm('Are you sure you want to delete this document?')) {
        $.post('api/delete_document.php', {id: id}, function(response) {
            if (response.success) {
                $('#documentsTable').DataTable().ajax.reload();
                loadDocumentStats();
                toastr.success('Document deleted successfully');
            } else {
                toastr.error(response.message);
            }
        });
    }
}
</script>

<?php require_once 'templates/footer.php'; ?>
