<?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('admin')) {
    header('Location: ../login.php');
    exit();
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_university'])) {
        // Add new university
        $name = $_POST['name'];
        $country_id = $_POST['country_id'];
        $city = $_POST['city'];
        $website = $_POST['website'];
        $description = $_POST['description'];
        $partnership_level = $_POST['partnership_level'];
        
        // Handle logo upload
        $logo_path = null;
        if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
            $upload_result = handleFileUpload($_FILES['logo'], 'universities');
            if ($upload_result['success']) {
                $logo_path = $upload_result['path'];
            } else {
                $_SESSION['error_message'] = $upload_result['error'];
                header("Location: universities.php");
                exit();
            }
        }
        
        try {
            $stmt = $pdo->prepare("INSERT INTO universities 
                                 (name, country_id, city, logo, website, description, partnership_level) 
                                 VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$name, $country_id, $city, $logo_path, $website, $description, $partnership_level]);
            
            $_SESSION['success_message'] = "University added successfully!";
        } catch (PDOException $e) {
            $_SESSION['error_message'] = "Error adding university: " . $e->getMessage();
        }
        
        header("Location: universities.php");
        exit();
    } elseif (isset($_POST['update_university'])) {
        // Update existing university
        $id = $_POST['id'];
        $name = $_POST['name'];
        $country_id = $_POST['country_id'];
        $city = $_POST['city'];
        $website = $_POST['website'];
        $description = $_POST['description'];
        $partnership_level = $_POST['partnership_level'];
        
        // Handle logo upload if new file provided
        $logo_update = '';
        $params = [$name, $country_id, $city, $website, $description, $partnership_level, $id];
        
        if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
            $upload_result = handleFileUpload($_FILES['logo'], 'universities');
            if ($upload_result['success']) {
                $logo_update = ', logo = ?';
                array_unshift($params, $upload_result['path']);
            } else {
                $_SESSION['error_message'] = $upload_result['error'];
                header("Location: universities.php");
                exit();
            }
        }
        
        try {
            $stmt = $pdo->prepare("UPDATE universities 
                                   SET name = ?, country_id = ?, city = ?, website = ?, 
                                   description = ?, partnership_level = ? $logo_update
                                   WHERE id = ?");
            $stmt->execute($params);
            
            $_SESSION['success_message'] = "University updated successfully!";
        } catch (PDOException $e) {
            $_SESSION['error_message'] = "Error updating university: " . $e->getMessage();
        }
        
        header("Location: universities.php");
        exit();
    } elseif (isset($_POST['delete_university'])) {
        // Delete university
        $id = $_POST['id'];
        
        try {
            $stmt = $pdo->prepare("DELETE FROM universities WHERE id = ?");
            $stmt->execute([$id]);
            
            $_SESSION['success_message'] = "University deleted successfully!";
        } catch (PDOException $e) {
            $_SESSION['error_message'] = "Error deleting university: " . $e->getMessage();
        }
        
        header("Location: universities.php");
        exit();
    }
}

// Get all universities with country data
$universities = $pdo->query("
    SELECT u.*, c.name AS country_name 
    FROM universities u
    JOIN countries c ON u.country_id = c.id
    ORDER BY u.name
")->fetchAll(PDO::FETCH_ASSOC);

// Get all countries for dropdown
$countries = $pdo->query("SELECT * FROM countries ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

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

<div class="container py-5">
    <h2 class="mb-4">University Management</h2>
    
    <?php displayMessages(); ?>
    
    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h4 class="mb-0">Partner Universities</h4>
            <button class="btn btn-primary" data-toggle="modal" data-target="#addUniversityModal">
                <i class="fas fa-plus"></i> Add University
            </button>
        </div>
        <div class="card-body">
            <?php if (count($universities) > 0): ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Logo</th>
                                <th>Name</th>
                                <th>Location</th>
                                <th>Partnership</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($universities as $uni): ?>
                                <tr>
                                    <td>
                                        <?php if ($uni['logo']): ?>
                                            <img src="../../<?= htmlspecialchars($uni['logo']) ?>" 
                                                 alt="<?= htmlspecialchars($uni['name']) ?>" 
                                                 style="max-height: 40px;">
                                        <?php else: ?>
                                            <span class="text-muted">No logo</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= htmlspecialchars($uni['name']) ?></td>
                                    <td>
                                        <?= htmlspecialchars($uni['city']) ?>, <?= htmlspecialchars($uni['country_name']) ?>
                                    </td>
                                    <td>
                                        <span class="badge badge-<?= 
                                            $uni['partnership_level'] == 'premium' ? 'success' : 
                                            ($uni['partnership_level'] == 'preferred' ? 'primary' : 'secondary') ?>">
                                            <?= ucfirst($uni['partnership_level']) ?>
                                        </span>
                                    </td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary edit-university" 
                                                data-id="<?= $uni['id'] ?>"
                                                data-name="<?= htmlspecialchars($uni['name']) ?>"
                                                data-country="<?= $uni['country_id'] ?>"
                                                data-city="<?= htmlspecialchars($uni['city']) ?>"
                                                data-website="<?= htmlspecialchars($uni['website']) ?>"
                                                data-description="<?= htmlspecialchars($uni['description']) ?>"
                                                data-partnership="<?= $uni['partnership_level'] ?>">
                                            Edit
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger delete-university" 
                                                data-id="<?= $uni['id'] ?>">
                                            Delete
                                        </button>
                                        <a href="university-programs.php?id=<?= $uni['id'] ?>" 
                                           class="btn btn-sm btn-outline-info">
                                            Programs
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="alert alert-info">
                    No universities found. Add your first partner university.
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Add University Modal -->
<div class="modal fade" id="addUniversityModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <form method="post" enctype="multipart/form-data">
                <div class="modal-header">
                    <h5 class="modal-title">Add New University</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="name">University Name</label>
                        <input type="text" class="form-control" id="name" name="name" required>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="country_id">Country</label>
                            <select class="form-control" id="country_id" name="country_id" required>
                                <option value="">Select country</option>
                                <?php foreach ($countries as $country): ?>
                                    <option value="<?= $country['id'] ?>"><?= htmlspecialchars($country['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group col-md-6">
                            <label for="city">City</label>
                            <input type="text" class="form-control" id="city" name="city" required>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="logo">University Logo</label>
                        <div class="custom-file">
                            <input type="file" class="custom-file-input" id="logo" name="logo">
                            <label class="custom-file-label" for="logo">Choose file</label>
                        </div>
                        <small class="form-text text-muted">
                            Recommended size: 300x100px (PNG or JPG)
                        </small>
                    </div>
                    
                    <div class="form-group">
                        <label for="website">Website URL</label>
                        <input type="url" class="form-control" id="website" name="website">
                    </div>
                    
                    <div class="form-group">
                        <label for="partnership_level">Partnership Level</label>
                        <select class="form-control" id="partnership_level" name="partnership_level" required>
                            <option value="basic">Basic</option>
                            <option value="preferred">Preferred</option>
                            <option value="premium">Premium</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="description">Description</label>
                        <textarea class="form-control" id="description" name="description" rows="4"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" name="add_university" class="btn btn-primary">Save University</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit University Modal -->
<div class="modal fade" id="editUniversityModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <form method="post" enctype="multipart/form-data">
                <input type="hidden" name="id" id="edit_id">
                <input type="hidden" name="update_university" value="1">
                
                <div class="modal-header">
                    <h5 class="modal-title">Edit University</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="edit_name">University Name</label>
                        <input type="text" class="form-control" id="edit_name" name="name" required>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="edit_country_id">Country</label>
                            <select class="form-control" id="edit_country_id" name="country_id" required>
                                <option value="">Select country</option>
                                <?php foreach ($countries as $country): ?>
                                    <option value="<?= $country['id'] ?>"><?= htmlspecialchars($country['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group col-md-6">
                            <label for="edit_city">City</label>
                            <input type="text" class="form-control" id="edit_city" name="city" required>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>Current Logo</label>
                        <div id="current_logo_container" class="mb-2"></div>
                        <label for="edit_logo">Upload New Logo</label>
                        <div class="custom-file">
                            <input type="file" class="custom-file-input" id="edit_logo" name="logo">
                            <label class="custom-file-label" for="edit_logo">Choose file</label>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="edit_website">Website URL</label>
                        <input type="url" class="form-control" id="edit_website" name="website">
                    </div>
                    
                    <div class="form-group">
                        <label for="edit_partnership_level">Partnership Level</label>
                        <select class="form-control" id="edit_partnership_level" name="partnership_level" required>
                            <option value="basic">Basic</option>
                            <option value="preferred">Preferred</option>
                            <option value="premium">Premium</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="edit_description">Description</label>
                        <textarea class="form-control" id="edit_description" name="description" rows="4"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update University</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteUniversityModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form method="post">
                <input type="hidden" name="id" id="delete_id">
                <input type="hidden" name="delete_university" value="1">
                
                <div class="modal-header">
                    <h5 class="modal-title">Confirm Deletion</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete this university? This action cannot be undone.</p>
                    <p>All associated programs will also be deleted.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete University</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Edit university modal
document.querySelectorAll('.edit-university').forEach(button => {
    button.addEventListener('click', function() {
        const modal = $('#editUniversityModal');
        modal.find('#edit_id').val(this.dataset.id);
        modal.find('#edit_name').val(this.dataset.name);
        modal.find('#edit_country_id').val(this.dataset.country);
        modal.find('#edit_city').val(this.dataset.city);
        modal.find('#edit_website').val(this.dataset.website);
        modal.find('#edit_partnership_level').val(this.dataset.partnership);
        modal.find('#edit_description').val(this.dataset.description);
        
        // Display current logo if exists
        const logoContainer = modal.find('#current_logo_container');
        logoContainer.empty();
        if (this.dataset.logo) {
            logoContainer.append(
                `<img src="../../${this.dataset.logo}" alt="Current Logo" style="max-height: 50px;">`
            );
        } else {
            logoContainer.append('<span class="text-muted">No logo uploaded</span>');
        }
        
        modal.modal('show');
    });
});

// Delete university modal
document.querySelectorAll('.delete-university').forEach(button => {
    button.addEventListener('click', function() {
        $('#delete_id').val(this.dataset.id);
        $('#deleteUniversityModal').modal('show');
    });
});

// Update file input labels
document.getElementById('logo').addEventListener('change', function(e) {
    document.querySelector('#addUniversityModal .custom-file-label').textContent = 
        e.target.files[0] ? e.target.files[0].name : 'Choose file';
});

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

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