<?php
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Authentication check
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
    header('Location: admin-login.php');
    exit;
}

// Get admin data
$stmt = $pdo->prepare("SELECT a.*, u.email FROM admins a JOIN users u ON a.id = u.id WHERE a.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin) {
    die("Admin profile not found.");
}

$error = '';
$success = '';
$upload_dir = 'uploads/universities/';
$flag_dir = 'img/flags/';

// Create upload directories if they don't exist with proper permissions
if (!file_exists($upload_dir)) {
    if (!mkdir($upload_dir, 0755, true)) {
        $error = "Failed to create university upload directory. Please check file permissions.";
    }
}

if (!file_exists($flag_dir)) {
    if (!mkdir($flag_dir, 0755, true)) {
        $error = "Failed to create flags directory. Please check file permissions.";
    }
}

// Get countries for dropdown
$countries = $pdo->query("SELECT id, name FROM countries ORDER BY name")->fetchAll();

// Handle university creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_university'])) {
    // Sanitize and validate input
    $name = trim($_POST['name'] ?? '');
    $country_id = (int)($_POST['country_id'] ?? 0);
    $city = trim($_POST['city'] ?? '');
    $ranking = !empty($_POST['ranking']) ? (int)$_POST['ranking'] : null;
    $website = filter_var(trim($_POST['website'] ?? ''), FILTER_SANITIZE_URL);
    $description = trim($_POST['description'] ?? '');
    $partnership_level = in_array($_POST['partnership_level'] ?? '', ['basic', 'preferred', 'premium']) 
                        ? $_POST['partnership_level'] : 'basic';
    $contact_name = trim($_POST['contact_name'] ?? '');
    $contact_email = filter_var(trim($_POST['contact_email'] ?? ''), FILTER_SANITIZE_EMAIL);
    $contact_phone = trim($_POST['contact_phone'] ?? '');
    $application_fee = !empty($_POST['application_fee']) ? (float)$_POST['application_fee'] : null;
    $intake_months = $_POST['intake_months'] ?? [];

    // Validate required fields
    if (empty($name) || $country_id <= 0) {
        $error = "University name and country are required fields.";
    } elseif ($application_fee !== null && $application_fee < 0) {
        $error = "Application fee must be a positive number.";
    } else {
        try {
            $pdo->beginTransaction();

            // Get country name for flag filename
            $country_stmt = $pdo->prepare("SELECT name FROM countries WHERE id = ?");
            $country_stmt->execute([$country_id]);
            $country_data = $country_stmt->fetch();
            $country_name = $country_data['name'];
            $flag_filename = strtolower(str_replace(' ', '', $country_name)) . '.png';

            // Insert university data
            $stmt = $pdo->prepare("INSERT INTO universities (
                name, country_id, city, ranking, website, description, 
                partnership_level, contact_name, contact_email, contact_phone, 
                application_fee, application_deadlines, created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");

            $stmt->execute([
                $name,
                $country_id,
                $city,
                $ranking,
                $website,
                $description,
                $partnership_level,
                $contact_name,
                $contact_email,
                $contact_phone,
                $application_fee,
                !empty($intake_months) ? json_encode($intake_months) : null
            ]);

            $university_id = $pdo->lastInsertId();

            // Handle logo upload (university-logo)
            $logo_path = null;
            if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
                $file_name = $_FILES['logo']['name'];
                $file_tmp = $_FILES['logo']['tmp_name'];
                $file_size = $_FILES['logo']['size'];
                $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                
                $allowed_exts = ['jpg', 'jpeg', 'png', 'gif', 'svg'];
                $max_size = 5 * 1024 * 1024; // 5MB

                // Validate file extension
                if (!in_array($file_ext, $allowed_exts)) {
                    throw new Exception("Invalid file type for logo. Only JPG, JPEG, PNG, GIF, and SVG are allowed.");
                }
                
                // Validate file size
                if ($file_size > $max_size) {
                    throw new Exception("Logo file size exceeds maximum limit of 5MB.");
                }
                
                // Create unique filename for logo
                $logo_file_name = "university_logo_{$university_id}_" . time() . ".{$file_ext}";
                $logo_file_path = $upload_dir . $logo_file_name;

                // Move uploaded logo file
                if (!move_uploaded_file($file_tmp, $logo_file_path)) {
                    // Get specific error message
                    switch ($_FILES['logo']['error']) {
                        case UPLOAD_ERR_INI_SIZE:
                            throw new Exception("Logo file size exceeds server limit (upload_max_filesize).");
                        case UPLOAD_ERR_FORM_SIZE:
                            throw new Exception("Logo file size exceeds form limit.");
                        case UPLOAD_ERR_PARTIAL:
                            throw new Exception("Logo file was only partially uploaded.");
                        case UPLOAD_ERR_NO_FILE:
                            throw new Exception("No logo file was uploaded.");
                        case UPLOAD_ERR_NO_TMP_DIR:
                            throw new Exception("Missing temporary folder for logo upload.");
                        case UPLOAD_ERR_CANT_WRITE:
                            throw new Exception("Failed to write logo file to disk.");
                        case UPLOAD_ERR_EXTENSION:
                            throw new Exception("Logo file upload stopped by extension.");
                        default:
                            throw new Exception("Unknown upload error for logo.");
                    }
                }

                // Verify the logo file was actually created
                if (!file_exists($logo_file_path)) {
                    throw new Exception("Failed to save uploaded logo file.");
                }

                // Set proper file permissions for logo
                chmod($logo_file_path, 0644);
                
                $logo_path = $logo_file_path;
            }

            // Handle banner image upload (university-img)
            $banner_path = null;
            if (isset($_FILES['banner_image']) && $_FILES['banner_image']['error'] === UPLOAD_ERR_OK) {
                $file_name = $_FILES['banner_image']['name'];
                $file_tmp = $_FILES['banner_image']['tmp_name'];
                $file_size = $_FILES['banner_image']['size'];
                $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                
                $allowed_exts = ['jpg', 'jpeg', 'png', 'gif'];
                $max_size = 10 * 1024 * 1024; // 10MB for banner images

                // Validate file extension
                if (!in_array($file_ext, $allowed_exts)) {
                    throw new Exception("Invalid file type for banner image. Only JPG, JPEG, PNG, and GIF are allowed.");
                }
                
                // Validate file size
                if ($file_size > $max_size) {
                    throw new Exception("Banner image size exceeds maximum limit of 10MB.");
                }
                
                // Create unique filename for banner
                $banner_file_name = "university_banner_{$university_id}_" . time() . ".{$file_ext}";
                $banner_file_path = $upload_dir . $banner_file_name;

                // Move uploaded banner file
                if (!move_uploaded_file($file_tmp, $banner_file_path)) {
                    // Get specific error message
                    switch ($_FILES['banner_image']['error']) {
                        case UPLOAD_ERR_INI_SIZE:
                            throw new Exception("Banner image size exceeds server limit (upload_max_filesize).");
                        case UPLOAD_ERR_FORM_SIZE:
                            throw new Exception("Banner image size exceeds form limit.");
                        case UPLOAD_ERR_PARTIAL:
                            throw new Exception("Banner image was only partially uploaded.");
                        case UPLOAD_ERR_NO_FILE:
                            throw new Exception("No banner image was uploaded.");
                        case UPLOAD_ERR_NO_TMP_DIR:
                            throw new Exception("Missing temporary folder for banner image upload.");
                        case UPLOAD_ERR_CANT_WRITE:
                            throw new Exception("Failed to write banner image to disk.");
                        case UPLOAD_ERR_EXTENSION:
                            throw new Exception("Banner image upload stopped by extension.");
                        default:
                            throw new Exception("Unknown upload error for banner image.");
                    }
                }

                // Verify the banner file was actually created
                if (!file_exists($banner_file_path)) {
                    throw new Exception("Failed to save uploaded banner image.");
                }

                // Set proper file permissions for banner
                chmod($banner_file_path, 0644);
                
                $banner_path = $banner_file_path;
            }

            // Handle country flag upload
            $flag_path = null;
            if (isset($_FILES['country_flag']) && $_FILES['country_flag']['error'] === UPLOAD_ERR_OK) {
                $file_name = $_FILES['country_flag']['name'];
                $file_tmp = $_FILES['country_flag']['tmp_name'];
                $file_size = $_FILES['country_flag']['size'];
                $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                
                $allowed_exts = ['jpg', 'jpeg', 'png', 'gif'];
                $max_size = 2 * 1024 * 1024; // 2MB for flag

                // Validate file extension
                if (!in_array($file_ext, $allowed_exts)) {
                    throw new Exception("Invalid file type for flag. Only JPG, JPEG, PNG, and GIF are allowed.");
                }
                
                // Validate file size
                if ($file_size > $max_size) {
                    throw new Exception("Flag image size exceeds maximum limit of 2MB.");
                }
                
                // Use standardized filename based on country name
                $flag_file_path = $flag_dir . $flag_filename;

                // Move uploaded flag file
                if (!move_uploaded_file($file_tmp, $flag_file_path)) {
                    // Get specific error message
                    switch ($_FILES['country_flag']['error']) {
                        case UPLOAD_ERR_INI_SIZE:
                            throw new Exception("Flag image size exceeds server limit (upload_max_filesize).");
                        case UPLOAD_ERR_FORM_SIZE:
                            throw new Exception("Flag image size exceeds form limit.");
                        case UPLOAD_ERR_PARTIAL:
                            throw new Exception("Flag image was only partially uploaded.");
                        case UPLOAD_ERR_NO_FILE:
                            throw new Exception("No flag image was uploaded.");
                        case UPLOAD_ERR_NO_TMP_DIR:
                            throw new Exception("Missing temporary folder for flag image upload.");
                        case UPLOAD_ERR_CANT_WRITE:
                            throw new Exception("Failed to write flag image to disk.");
                        case UPLOAD_ERR_EXTENSION:
                            throw new Exception("Flag image upload stopped by extension.");
                        default:
                            throw new Exception("Unknown upload error for flag image.");
                    }
                }

                // Verify the flag file was actually created
                if (!file_exists($flag_file_path)) {
                    throw new Exception("Failed to save uploaded flag image.");
                }

                // Set proper file permissions for flag
                chmod($flag_file_path, 0644);
                
                $flag_path = $flag_file_path;
            }

            // Update university with logo and banner paths
            $pdo->prepare("UPDATE universities SET logo = ?, banner_image = ? WHERE id = ?")
                ->execute([$logo_path, $banner_path, $university_id]);

            // Log the activity
            $pdo->prepare("INSERT INTO activities (
                user_id, activity_type, description, created_at
            ) VALUES (?, ?, ?, NOW())")->execute([
                $_SESSION['user_id'],
                "university_created",
                "Created university: {$name}" . 
                ($logo_path ? " with logo" : " without logo") . 
                ($banner_path ? " with banner image" : " without banner image") .
                ($flag_path ? " with country flag" : " country flag unchanged")
            ]);

            $pdo->commit();

            $_SESSION['success'] = "University created successfully!";
            header("Location: admin-university-profile.php?id={$university_id}");
            exit;

        } catch (PDOException $e) {
            $pdo->rollBack();
            $error = "Database error: " . $e->getMessage();
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = $e->getMessage();
        }
    }
}

// Display success message from session if redirected
if (isset($_SESSION['success'])) {
    $success = $_SESSION['success'];
    unset($_SESSION['success']);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Create University - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .form-section {
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }
        .section-title {
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #3fb7fe;
        }
        .file-upload {
            position: relative;
            border: 2px dashed #dee2e6;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        .file-upload:hover {
            border-color: #3fb7fe;
            background: #f8f9fa;
        }
        .file-input {
            display: none;
        }
        .partner-badge {
            font-size: 0.9em;
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
            display: inline-block;
            margin-right: 5px;
        }
        .partner-basic {
            background: #f8f9fa;
            color: #6c757d;
        }
        .partner-preferred {
            background: #fff3cd;
            color: #856404;
        }
        .partner-premium {
            background: #d1ecf1;
            color: #0c5460;
        }
        .checkbox-group {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 10px;
        }
        .checkbox-item {
            margin-bottom: 10px;
        }
        .preview-image {
            max-width: 100%;
            max-height: 150px;
            margin-top: 10px;
            border-radius: 5px;
            display: none;
        }
        .upload-info {
            margin-top: 10px;
            font-size: 0.8em;
            color: #666;
        }
        .image-preview-container {
            display: flex;
            gap: 20px;
            margin-top: 15px;
        }
        .image-preview {
            flex: 1;
            text-align: center;
        }
        .image-preview h6 {
            margin-bottom: 10px;
            color: #333;
        }
        .logo-preview {
            max-width: 120px;
            max-height: 120px;
            object-fit: contain;
            background: white;
            padding: 10px;
            border-radius: 10px;
            border: 1px solid #ddd;
        }
        .banner-preview {
            width: 100%;
            max-height: 100px;
            object-fit: cover;
            border-radius: 5px;
            border: 1px solid #ddd;
        }
        .flag-preview {
            width: 100%;
            max-height: 80px;
            object-fit: contain;
            border-radius: 5px;
            border: 1px solid #ddd;
        }
    </style>
</head>
<body>

<?php include 'admin-navbar.php'; ?>

<div class="container py-5">
    <div class="section-title position-relative mb-4">
        <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Academic Management</h6>
        <h1 class="display-5">Create New University</h1>
    </div>

    <?php if ($error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    
    <?php if ($success): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data" id="universityForm">
        <!-- University Information Section -->
        <div class="form-section">
            <h5 class="section-title">University Information</h5>
            <div class="row">
                <div class="col-md-8 mb-3">
                    <label>University Name *</label>
                    <input type="text" name="name" class="form-control" required
                           value="<?= htmlspecialchars($_POST['name'] ?? '') ?>">
                </div>
                <div class="col-md-4 mb-3">
                    <label>Country *</label>
                    <select name="country_id" class="form-control" required>
                        <option value="">Select Country</option>
                        <?php foreach ($countries as $c): ?>
                        <option value="<?= $c['id'] ?>" 
                            <?= ($c['id'] == ($_POST['country_id'] ?? '')) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($c['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>City</label>
                    <input type="text" name="city" class="form-control"
                           value="<?= htmlspecialchars($_POST['city'] ?? '') ?>">
                </div>
                <div class="col-md-6 mb-3">
                    <label>Ranking</label>
                    <input type="number" name="ranking" class="form-control" min="1"
                           value="<?= htmlspecialchars($_POST['ranking'] ?? '') ?>">
                    <small class="form-text text-muted">World university ranking (e.g., 50 for top 50)</small>
                </div>
            </div>
            <div class="form-group mb-3">
                <label>Website</label>
                <input type="url" name="website" class="form-control" 
                       value="<?= htmlspecialchars($_POST['website'] ?? '') ?>"
                       placeholder="https://www.university.edu">
            </div>
            <div class="form-group mb-3">
                <label>Description</label>
                <textarea name="description" class="form-control" rows="4"><?= 
                    htmlspecialchars($_POST['description'] ?? '') 
                ?></textarea>
            </div>
            
            <!-- University Images Section -->
            <div class="row">
                <!-- University Logo Upload -->
                <div class="col-md-4 mb-3">
                    <label>University Logo (.university-logo)</label>
                    <div class="file-upload" id="logoUpload">
                        <i class="fas fa-file-image fa-2x mb-3" style="color: #3fb7fe;"></i>
                        <h6>Upload Logo</h6>
                        <p class="text-muted small">JPG, PNG, GIF, or SVG (max 5MB)</p>
                        <div class="image-preview">
                            <img id="logoPreview" class="logo-preview" alt="Logo preview">
                        </div>
                        <input type="file" name="logo" id="logoFile" class="file-input" accept="image/*">
                        <div class="upload-info" id="logoUploadInfo"></div>
                    </div>
                </div>
                
                <!-- University Banner Image Upload -->
                <div class="col-md-4 mb-3">
                    <label>University Banner Image (.university-img)</label>
                    <div class="file-upload" id="bannerUpload">
                        <i class="fas fa-image fa-2x mb-3" style="color: #3fb7fe;"></i>
                        <h6>Upload Banner</h6>
                        <p class="text-muted small">JPG, PNG, or GIF (max 10MB)</p>
                        <div class="image-preview">
                            <img id="bannerPreview" class="banner-preview" alt="Banner preview">
                        </div>
                        <input type="file" name="banner_image" id="bannerFile" class="file-input" accept="image/*">
                        <div class="upload-info" id="bannerUploadInfo"></div>
                    </div>
                </div>
                
                <!-- Country Flag Upload -->
                <div class="col-md-4 mb-3">
                    <label>Country Flag Image</label>
                    <div class="file-upload" id="flagUpload">
                        <i class="fas fa-flag fa-2x mb-3" style="color: #3fb7fe;"></i>
                        <h6>Upload Flag</h6>
                        <p class="text-muted small">JPG, PNG, or GIF (max 2MB)</p>
                        <div class="image-preview">
                            <img id="flagPreview" class="flag-preview" alt="Flag preview">
                        </div>
                        <input type="file" name="country_flag" id="flagFile" class="file-input" accept="image/*">
                        <div class="upload-info" id="flagUploadInfo"></div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Partnership Information Section -->
        <div class="form-section">
            <h5 class="section-title">Partnership Information</h5>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Partnership Level</label>
                    <select name="partnership_level" class="form-control">
                        <option value="basic" <?= ($_POST['partnership_level'] ?? 'basic') === 'basic' ? 'selected' : '' ?>>Basic</option>
                        <option value="preferred" <?= ($_POST['partnership_level'] ?? 'basic') === 'preferred' ? 'selected' : '' ?>>Preferred</option>
                        <option value="premium" <?= ($_POST['partnership_level'] ?? 'basic') === 'premium' ? 'selected' : '' ?>>Premium</option>
                    </select>
                    <div class="mt-2">
                        <span class="partner-badge partner-basic">Basic</span>
                        <span class="partner-badge partner-preferred">Preferred</span>
                        <span class="partner-badge partner-premium">Premium</span>
                    </div>
                </div>
                <div class="col-md-6 mb-3">
                    <label>Application Fee (USD)</label>
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <span class="input-group-text">$</span>
                        </div>
                        <input type="number" name="application_fee" class="form-control" step="0.01" min="0"
                               value="<?= htmlspecialchars($_POST['application_fee'] ?? '') ?>">
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label>Application Deadlines</label>
                <div class="checkbox-group">
                    <?php 
                    $months = [
                        'January', 'February', 'March', 'April', 'May', 'June',
                        'July', 'August', 'September', 'October', 'November', 'December'
                    ];
                    $selected_months = $_POST['intake_months'] ?? [];
                    ?>
                    <?php foreach ($months as $month): ?>
                    <div class="checkbox-item">
                        <div class="custom-control custom-checkbox">
                            <input type="checkbox" class="custom-control-input" 
                                   name="intake_months[]" 
                                   value="<?= $month ?>" 
                                   id="<?= strtolower($month) ?>"
                                   <?= in_array($month, $selected_months) ? 'checked' : '' ?>>
                            <label class="custom-control-label" for="<?= strtolower($month) ?>"><?= $month ?></label>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        
        <!-- Contact Information Section -->
        <div class="form-section">
            <h5 class="section-title">Contact Information</h5>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Contact Name</label>
                    <input type="text" name="contact_name" class="form-control"
                           value="<?= htmlspecialchars($_POST['contact_name'] ?? '') ?>">
                </div>
                <div class="col-md-6 mb-3">
                    <label>Contact Email</label>
                    <input type="email" name="contact_email" class="form-control"
                           value="<?= htmlspecialchars($_POST['contact_email'] ?? '') ?>">
                </div>
            </div>
            <div class="form-group">
                <label>Contact Phone</label>
                <input type="text" name="contact_phone" class="form-control"
                       value="<?= htmlspecialchars($_POST['contact_phone'] ?? '') ?>">
            </div>
        </div>
        
        <!-- Form Submission -->
        <div class="text-center mt-4">
            <button type="submit" name="create_university" class="btn btn-primary btn-lg px-5">
                <i class="fas fa-plus-circle mr-2"></i> Create University
            </button>
            <a href="admin-universities.php" class="btn btn-outline-secondary ml-2">Cancel</a>
        </div>
    </form>
</div>

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

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
<script>
$(document).ready(function() {
    // Make the entire upload area clickable for logo
    $('#logoUpload').click(function(e) {
        // Prevent the click from triggering on the input itself
        if (e.target.id !== 'logoFile') {
            e.preventDefault();
            $('#logoFile').click();
        }
    });
    
    // Make the entire upload area clickable for banner
    $('#bannerUpload').click(function(e) {
        // Prevent the click from triggering on the input itself
        if (e.target.id !== 'bannerFile') {
            e.preventDefault();
            $('#bannerFile').click();
        }
    });
    
    // Make the entire upload area clickable for flag
    $('#flagUpload').click(function(e) {
        // Prevent the click from triggering on the input itself
        if (e.target.id !== 'flagFile') {
            e.preventDefault();
            $('#flagFile').click();
        }
    });
    
    // Logo upload preview and file info
    $('#logoFile').change(function(e) {
        const file = e.target.files[0];
        if (file) {
            // Display file info
            $('#logoUploadInfo').html(`
                <strong>File:</strong> ${file.name} <br>
                <strong>Size:</strong> ${(file.size / 1024).toFixed(1)} KB <br>
                <strong>Type:</strong> ${file.type}
            `);
            
            // Show image preview if it's an image
            if (file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    $('#logoPreview').attr('src', e.target.result).show();
                    $('#logoUpload i, #logoUpload h6, #logoUpload p').hide();
                };
                reader.readAsDataURL(file);
            } else {
                // For non-image files, show generic icon
                $('#logoPreview').hide();
                $('#logoUpload i').show();
                $('#logoUpload h6').text('File Selected');
                $('#logoUpload p').text(file.name);
            }
        } else {
            // Reset if no file selected
            resetLogoUploadDisplay();
        }
    });
    
    // Banner image upload preview and file info
    $('#bannerFile').change(function(e) {
        const file = e.target.files[0];
        if (file) {
            // Display file info
            $('#bannerUploadInfo').html(`
                <strong>File:</strong> ${file.name} <br>
                <strong>Size:</strong> ${(file.size / 1024).toFixed(1)} KB <br>
                <strong>Type:</strong> ${file.type}
            `);
            
            // Show image preview if it's an image
            if (file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    $('#bannerPreview').attr('src', e.target.result).show();
                    $('#bannerUpload i, #bannerUpload h6, #bannerUpload p').hide();
                };
                reader.readAsDataURL(file);
            } else {
                // For non-image files, show generic icon
                $('#bannerPreview').hide();
                $('#bannerUpload i').show();
                $('#bannerUpload h6').text('File Selected');
                $('#bannerUpload p').text(file.name);
            }
        } else {
            // Reset if no file selected
            resetBannerUploadDisplay();
        }
    });
    
    // Flag image upload preview and file info
    $('#flagFile').change(function(e) {
        const file = e.target.files[0];
        if (file) {
            // Display file info
            $('#flagUploadInfo').html(`
                <strong>File:</strong> ${file.name} <br>
                <strong>Size:</strong> ${(file.size / 1024).toFixed(1)} KB <br>
                <strong>Type:</strong> ${file.type}
            `);
            
            // Show image preview if it's an image
            if (file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    $('#flagPreview').attr('src', e.target.result).show();
                    $('#flagUpload i, #flagUpload h6, #flagUpload p').hide();
                };
                reader.readAsDataURL(file);
            } else {
                // For non-image files, show generic icon
                $('#flagPreview').hide();
                $('#flagUpload i').show();
                $('#flagUpload h6').text('File Selected');
                $('#flagUpload p').text(file.name);
            }
        } else {
            // Reset if no file selected
            resetFlagUploadDisplay();
        }
    });
    
    // Reset upload displays
    function resetLogoUploadDisplay() {
        $('#logoPreview').hide();
        $('#logoUploadInfo').html('');
        $('#logoUpload i').show();
        $('#logoUpload h6').text('Upload Logo');
        $('#logoUpload p').text('JPG, PNG, GIF, or SVG (max 5MB)');
    }
    
    function resetBannerUploadDisplay() {
        $('#bannerPreview').hide();
        $('#bannerUploadInfo').html('');
        $('#bannerUpload i').show();
        $('#bannerUpload h6').text('Upload Banner');
        $('#bannerUpload p').text('JPG, PNG, or GIF (max 10MB)');
    }
    
    function resetFlagUploadDisplay() {
        $('#flagPreview').hide();
        $('#flagUploadInfo').html('');
        $('#flagUpload i').show();
        $('#flagUpload h6').text('Upload Flag');
        $('#flagUpload p').text('JPG, PNG, or GIF (max 2MB)');
    }

    // Form submission confirmation
    $('#universityForm').submit(function(e) {
        const name = $('input[name="name"]').val();
        const country = $('select[name="country_id"]').val();
        
        if (!name || !country) {
            e.preventDefault();
            alert('Please fill in all required fields (name and country).');
            return false;
        }
        
        // Check if logo file is too large
        if ($('#logoFile')[0].files.length > 0) {
            const file = $('#logoFile')[0].files[0];
            if (file.size > 5 * 1024 * 1024) {
                e.preventDefault();
                alert('The logo file is too large. Maximum size is 5MB.');
                return false;
            }
        }
        
        // Check if banner file is too large
        if ($('#bannerFile')[0].files.length > 0) {
            const file = $('#bannerFile')[0].files[0];
            if (file.size > 10 * 1024 * 1024) {
                e.preventDefault();
                alert('The banner image is too large. Maximum size is 10MB.');
                return false;
            }
        }
        
        // Check if flag file is too large
        if ($('#flagFile')[0].files.length > 0) {
            const file = $('#flagFile')[0].files[0];
            if (file.size > 2 * 1024 * 1024) {
                e.preventDefault();
                alert('The flag image is too large. Maximum size is 2MB.');
                return false;
            }
        }
        
        return confirm(`Are you sure you want to create the university "${name}"?`);
    });

    // Auto-select current month for intake
    const currentMonth = new Date().toLocaleString('default', { month: 'long' });
    $(`input[name="intake_months[]"][value="${currentMonth}"]`).prop('checked', true);
});
</script>
</body>
</html>