<?php
require_once __DIR__ . '/../../includes/dashboard-config.php';

// For role-specific pages, add:
checkRoleAccess(ROLE_STUDENT); // or ROLE_COUNSELOR or ROLE_ADMIN
require_once '../../includes/config.php';
require_once '../../includes/auth.php';
require_once '../../includes/functions.php';

if (!isLoggedIn() || !hasRole('student')) {
    header('Location: ../login.php');
    exit();
}

$student_id = $_SESSION['user_id'];

// Handle file upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['document'])) {
    $document_type = $_POST['document_type'];
    $expiry_date = !empty($_POST['expiry_date']) ? $_POST['expiry_date'] : null;
    
    $upload_result = handleFileUpload($_FILES['document'], 'students/'.$student_id);
    
    if ($upload_result['success']) {
        $stmt = $pdo->prepare("INSERT INTO student_documents 
                              (student_id, document_type, file_path, expiry_date) 
                              VALUES (?, ?, ?, ?)");
        $stmt->execute([$student_id, $document_type, $upload_result['path'], $expiry_date]);
        
        $_SESSION['success_message'] = "Document uploaded successfully!";
    } else {
        $_SESSION['error_message'] = $upload_result['error'];
    }
    
    header("Location: documents.php");
    exit();
}

// Get student documents
$stmt = $pdo->prepare("SELECT * FROM student_documents WHERE student_id = ? ORDER BY created_at DESC");
$stmt->execute([$student_id]);
$documents = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get document checklist
$stmt = $pdo->prepare("SELECT DISTINCT document_type FROM visa_checklist");
$stmt->execute();
$document_types = $stmt->fetchAll(PDO::FETCH_COLUMN);

include '../../includes/header.php';
?>

<div class="container py-5">
    <h2 class="mb-4">Document Center</h2>
    
    <?php displayMessages(); ?>
    
    <div class="card mb-4">
        <div class="card-header">
            <h4>Upload New Document</h4>
        </div>
        <div class="card-body">
            <form method="post" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="document_type">Document Type</label>
                    <select class="form-control" id="document_type" name="document_type" required>
                        <option value="">Select document type</option>
                        <?php foreach ($document_types as $type): ?>
                            <option value="<?= htmlspecialchars($type) ?>"><?= ucwords(str_replace('_', ' ', $type)) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="expiry_date">Expiry Date (if applicable)</label>
                    <input type="date" class="form-control" id="expiry_date" name="expiry_date">
                </div>
                
                <div class="form-group">
                    <label for="document">Document File</label>
                    <div class="custom-file">
                        <input type="file" class="custom-file-input" id="document" name="document" required>
                        <label class="custom-file-label" for="document">Choose file</label>
                    </div>
                    <small class="form-text text-muted">
                        Allowed file types: PDF, DOC, DOCX, JPG, PNG (Max 5MB)
                    </small>
                </div>
                
                <button type="submit" class="btn btn-primary">Upload Document</button>
            </form>
        </div>
    </div>
    
    <div class="card">
        <div class="card-header">
            <h4>My Documents</h4>
        </div>
        <div class="card-body">
            <?php if (count($documents) > 0): ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Document Type</th>
                                <th>File</th>
                                <th>Status</th>
                                <th>Uploaded</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($documents as $doc): ?>
                                <tr>
                                    <td><?= ucwords(str_replace('_', ' ', $doc['document_type'])) ?></td>
                                    <td>
                                        <a href="../../download.php?file=<?= urlencode($doc['file_path']) ?>" target="_blank">
                                            View Document
                                        </a>
                                    </td>
                                    <td>
                                        <span class="badge badge-<?= 
                                            $doc['status'] == 'approved' ? 'success' : 
                                            ($doc['status'] == 'rejected' ? 'danger' : 'warning') ?>">
                                            <?= ucfirst($doc['status']) ?>
                                        </span>
                                        <?php if ($doc['status'] == 'rejected' && !empty($doc['review_notes'])): ?>
                                            <small class="d-block text-muted"><?= htmlspecialchars($doc['review_notes']) ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= date('M j, Y', strtotime($doc['created_at'])) ?></td>
                                    <td>
                                        <a href="../../download.php?file=<?= urlencode($doc['file_path']) ?>" 
                                           class="btn btn-sm btn-outline-primary" download>
                                            Download
                                        </a>
                                        <?php if ($doc['status'] != 'approved'): ?>
                                            <button class="btn btn-sm btn-outline-danger delete-document" 
                                                    data-id="<?= $doc['id'] ?>">
                                                Delete
                                            </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="alert alert-info">
                    You haven't uploaded any documents yet.
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
// Document deletion
document.querySelectorAll('.delete-document').forEach(button => {
    button.addEventListener('click', function() {
        if (confirm('Are you sure you want to delete this document?')) {
            const docId = this.getAttribute('data-id');
            fetch(`../../api/documents.php?id=${docId}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    location.reload();
                } else {
                    alert('Error deleting document: ' + data.message);
                }
            });
        }
    });
});

// Update file input label
document.getElementById('document').addEventListener('change', function(e) {
    const fileName = e.target.files[0] ? e.target.files[0].name : 'Choose file';
    document.querySelector('.custom-file-label').textContent = fileName;
});
</script>

<?php include '../../includes/footer.php'; ?>