<?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.");
}

// Get university ID from URL
$university_id = $_GET['id'] ?? null;

if (!$university_id) {
    die("University ID is required.");
}

// Get university data
$stmt = $pdo->prepare("SELECT u.*, c.name as country_name, c.flag_path
                      FROM universities u
                      JOIN countries c ON u.country_id = c.id
                      WHERE u.id = ?");
$stmt->execute([$university_id]);
$university = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$university) {
    die("University not found.");
}

// Get programs for this university
$stmt = $pdo->prepare("SELECT p.*, 
                      CASE 
                          WHEN p.degree_level = 'bachelors' THEN 'Bachelor\'s'
                          WHEN p.degree_level = 'masters' THEN 'Master\'s'
                          ELSE UPPER(LEFT(p.degree_level, 1)) || LOWER(SUBSTRING(p.degree_level, 2))
                      END as degree_level_display
                      FROM programs p
                      WHERE p.university_id = ?
                      ORDER BY p.degree_level, p.name");
$stmt->execute([$university_id]);
$programs = $stmt->fetchAll();

// Get application deadlines
$application_deadlines = json_decode($university['application_deadlines'] ?? '[]', true);

// Get stats for this university
$stats = [
    'total_applications' => $pdo->query("SELECT COUNT(*) FROM applications a JOIN programs p ON a.program_id = p.id WHERE p.university_id = {$university_id}")->fetchColumn(),
    'accepted_applications' => $pdo->query("SELECT COUNT(*) FROM applications a JOIN programs p ON a.program_id = p.id WHERE p.university_id = {$university_id} AND a.application_status = 'accepted'")->fetchColumn(),
    'total_students' => $pdo->query("SELECT COUNT(DISTINCT s.id) FROM students s JOIN applications a ON s.id = a.student_id JOIN programs p ON a.program_id = p.id WHERE p.university_id = {$university_id} AND a.application_status = 'accepted'")->fetchColumn(),
    'total_scholarships' => $pdo->query("SELECT COALESCE(SUM(a.scholarship_awarded), 0) FROM applications a JOIN programs p ON a.program_id = p.id WHERE p.university_id = {$university_id} AND a.scholarship_awarded > 0")->fetchColumn(),
];

// Handle form submissions (update university)
$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_university'])) {
    $name = trim($_POST['name'] ?? '');
    $country_id = $_POST['country_id'] ?? null;
    $city = $_POST['city'] ?? '';
    $ranking = $_POST['ranking'] ?? null;
    $website = $_POST['website'] ?? '';
    $description = $_POST['description'] ?? '';
    $partnership_level = $_POST['partnership_level'] ?? 'basic';
    $contact_name = $_POST['contact_name'] ?? '';
    $contact_email = $_POST['contact_email'] ?? '';
    $contact_phone = $_POST['contact_phone'] ?? '';
    $application_fee = $_POST['application_fee'] ?? null;
    
    // Validate form data
    if (empty($name) || !$country_id) {
        $error = "University name and country are required.";
    } elseif ($application_fee !== null && (!is_numeric($application_fee) || $application_fee < 0)) {
        $error = "Application fee must be zero or a positive number.";
    } else {
        try {
            // Start transaction
            $pdo->beginTransaction();
            
            // Update university
            $stmt = $pdo->prepare("UPDATE universities SET 
                name = ?, country_id = ?, city = ?, ranking = ?, website = ?, description = ?, 
                partnership_level = ?, contact_name = ?, contact_email = ?, contact_phone = ?, 
                application_fee = ?, updated_at = NOW()
                WHERE id = ?");
            
            $stmt->execute([
                $name, $country_id, $city, $ranking, $website, $description, $partnership_level,
                $contact_name, $contact_email, $contact_phone, $application_fee, $university_id
            ]);
            
            // Handle logo upload
            if (isset($_FILES['logo']) && $_FILES['logo']['name']) {
                $upload_dir = 'uploads/universities/';
                if (!file_exists($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }
                
                $file_name = $_FILES['logo']['name'];
                $file_tmp = $_FILES['logo']['tmp_name'];
                $file_size = $_FILES['logo']['size'];
                $file_error = $_FILES['logo']['error'];
                
                if ($file_error === UPLOAD_ERR_OK && $file_size <= 5 * 1024 * 1024) {
                    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                    $allowed_exts = ['jpg', 'jpeg', 'png', 'gif', 'svg'];
                    
                    if (in_array($file_ext, $allowed_exts)) {
                        $unique_name = $university_id . '_logo_' . time() . '.' . $file_ext;
                        $file_path = $upload_dir . $unique_name;
                        
                        if (move_uploaded_file($file_tmp, $file_path)) {
                            // Update university with new logo path
                            $pdo->prepare("UPDATE universities SET logo = ? WHERE id = ?")
                                ->execute([$file_path, $university_id]);
                        }
                    }
                }
            }
            
            // Handle application deadlines
            $intake_months = $_POST['intake_months'] ?? [];
            if ($intake_months) {
                $pdo->prepare("UPDATE universities SET application_deadlines = ? WHERE id = ?")
                    ->execute([json_encode($intake_months), $university_id]);
            }
            
            // Log the activity
            $pdo->prepare("INSERT INTO activities (
                user_id, activity_type, description, created_at
            ) VALUES (?, ?, ?, NOW())")->execute([
                $_SESSION['user_id'],
                "university_updated",
                "Admin {$_SESSION['first_name']} {$_SESSION['last_name']} updated university: {$name}"
            ]);
            
            // Commit transaction
            $pdo->commit();
            
            $success = "University updated successfully!";
            
            // Refresh university data
            $stmt = $pdo->prepare("SELECT u.*, c.name as country_name, c.flag_path
                                  FROM universities u
                                  JOIN countries c ON u.country_id = c.id
                                  WHERE u.id = ?");
            $stmt->execute([$university_id]);
            $university = $stmt->fetch(PDO::FETCH_ASSOC);
            
        } catch (Exception $e) {
            $pdo->rollback();
            $error = "Failed to update university. Please try again.";
        }
    }
}

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title><?= htmlspecialchars($university['name']) ?> - 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>
        .university-header {
            background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('<?= htmlspecialchars($university['logo'] ?: 'img/university-placeholder.png') ?>');
            background-size: cover;
            background-position: center;
            color: white;
            padding: 80px 0;
            margin-bottom: 30px;
        }
        .university-logo-large {
            width: 150px;
            height: 150px;
            object-fit: contain;
            background: white;
            padding: 15px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        .partner-badge {
            font-size: 0.9em;
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
        }
        .partner-basic {
            background: #f8f9fa;
            color: #6c757d;
        }
        .partner-preferred {
            background: #fff3cd;
            color: #856404;
        }
        .partner-premium {
            background: #d1ecf1;
            color: #0c5460;
        }
        .program-card {
            border: 1px solid #eee;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            transition: all 0.3s;
        }
        .program-card:hover {
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            transform: translateY(-5px);
        }
        .degree-badge {
            font-size: 0.9em;
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
        }
        .degree-bachelors {
            background: #d1ecf1;
            color: #0c5460;
        }
        .degree-masters {
            background: #d4edda;
            color: #155724;
        }
        .degree-phd {
            background: #f8d7da;
            color: #721c24;
        }
        .degree-diploma {
            background: #fff3cd;
            color: #856404;
        }
        .degree-certificate {
            background: #d6d8d9;
            color: #383d41;
        }
        .deadline-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
        }
        .deadline-item:last-child {
            border-bottom: none;
        }
        .stat-card {
            border-left: 5px solid #3fb7fe;
            margin-bottom: 20px;
        }
        .file-upload {
            position: relative;
            border: 2px dashed #dee2e6;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
        }
        .file-upload:hover {
            border-color: #3fb7fe;
            background: #f8f9fa;
        }
        .file-input {
            display: none;
        }
    </style>
</head>
<body>

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

<!-- University Header -->
<div class="university-header">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-lg-8">
                <h1 class="display-4"><?= htmlspecialchars($university['name']) ?></h1>
                <div class="d-flex align-items-center mb-3">
                    <img src="img/flags/<?= strtolower($university['country_name']) ?>.png" 
                         alt="<?= htmlspecialchars($university['country_name']) ?>" class="country-flag">
                    <span><?= htmlspecialchars($university['city'] ?? $university['country_name']) ?></span>
                    <?php if ($university['ranking']): ?>
                    <span class="ml-3">#<?= $university['ranking'] ?> Worldwide</span>
                    <?php endif; ?>
                </div>
                <div class="d-flex align-items-center">
                    <span class="partner-badge partner-<?= strtolower($university['partnership_level'] ?: 'basic') ?>">
                        <?= ucfirst($university['partnership_level'] ?: 'Basic') ?> Partner
                    </span>
                    <?php if ($university['application_fee']): ?>
                    <span class="ml-3">Application Fee: $<?= number_format($university['application_fee'], 2) ?></span>
                    <?php endif; ?>
                </div>
            </div>
            <div class="col-lg-4 text-center">
                <img src="<?= htmlspecialchars($university['logo'] ?: 'img/university-placeholder.png') ?>" 
                     alt="<?= htmlspecialchars($university['name']) ?>" class="university-logo-large">
            </div>
        </div>
    </div>
</div>

<div class="container py-5">
    <div class="row">
        <div class="col-lg-8">
            <!-- Edit Form -->
            <div class="section-card mb-5">
                <div class="section-header">Edit University Information</div>
                <div class="section-body">
                    <?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">
                        <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" 
                                           value="<?= htmlspecialchars($university['name']) ?>" required>
                                </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 
                                        $countries = $pdo->query("SELECT id, name FROM countries ORDER BY name")->fetchAll();
                                        foreach ($countries as $c): ?>
                                        <option value="<?= $c['id'] ?>" <?= ($c['id'] == $university['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($university['city'] ?? '') ?>">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label>Ranking</label>
                                    <input type="number" name="ranking" class="form-control" min="1" max="1000"
                                           value="<?= htmlspecialchars($university['ranking'] ?? '') ?>">
                                    <small class="form-text text-muted">World university ranking (e.g., 50 for top 50)</small>
                                </div>
                            </div>
                            <div class="form-group">
                                <label>Website</label>
                                <input type="url" name="website" class="form-control" 
                                       value="<?= htmlspecialchars($university['website'] ?? '') ?>"
                                       placeholder="https://www.university.edu">
                            </div>
                            <div class="form-group">
                                <label>Description</label>
                                <textarea name="description" class="form-control" rows="4" 
                                          placeholder="Brief description of the university"><?= htmlspecialchars($university['description'] ?? '') ?></textarea>
                            </div>
                            <div class="form-group">
                                <label>University Logo</label>
                                <div class="file-upload" id="logoUpload">
                                    <i class="fas fa-file-upload fa-3x mb-3" style="color: #3fb7fe;"></i>
                                    <h6>Upload New Logo</h6>
                                    <p class="text-muted small">JPG, PNG, or SVG (max 5MB)</p>
                                    <input type="file" name="logo" id="logoFile" class="file-input" accept="image/*">
                                </div>
                                <small class="form-text text-muted">Optional: Upload a new logo for the university</small>
                            </div>
                        </div>
                        
                        <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" <?= ($university['partnership_level'] ?? 'basic') === 'basic' ? 'selected' : '' ?>>Basic</option>
                                        <option value="preferred" <?= ($university['partnership_level'] ?? 'basic') === 'preferred' ? 'selected' : '' ?>>Preferred</option>
                                        <option value="premium" <?= ($university['partnership_level'] ?? 'basic') === 'premium' ? 'selected' : '' ?>>Premium</option>
                                    </select>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label>Application Fee</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($university['application_fee'] ?? '') ?>">
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label>Application Deadlines</label>
                                <div class="row">
                                    <?php 
                                    $all_months = ['January', 'February', 'March', 'April', 'May', 'June', 
                                                  'July', 'August', 'September', 'October', 'November', 'December'];
                                    ?>
                                    <?php foreach ($all_months as $month): ?>
                                    <div class="col-md-4 mb-2">
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox" class="custom-control-input" name="intake_months[]" value="<?= $month ?>" id="<?= strtolower($month) ?>" <?= in_array($month, $application_deadlines) ? 'checked' : '' ?>>
                                            <label class="custom-control-label" for="<?= strtolower($month) ?>"><?= $month ?></label>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                        
                        <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($university['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($university['contact_email'] ?? '') ?>">
                                </div>
                            </div>
                            <div class="form-group">
                                <label>Contact Phone</label>
                                <input type="text" name="contact_phone" class="form-control" 
                                       value="<?= htmlspecialchars($university['contact_phone'] ?? '') ?>">
                            </div>
                        </div>
                        
                        <div class="text-center">
                            <button type="submit" name="update_university" class="btn btn-primary btn-lg px-5">Update University</button>
                        </div>
                        
                        <div class="text-center mt-3">
                            <a href="admin-universities.php" class="btn btn-outline-primary">Cancel</a>
                        </div>
                    </form>
                </div>
            </div>
            
            <!-- Programs Section -->
            <div class="section-card">
                <div class="section-header">
                    Programs (<?= count($programs) ?>)
                    <a href="admin-create-program.php?university_id=<?= $university_id ?>" class="btn btn-primary btn-sm float-right">Add Program</a>
                </div>
                <div class="section-body">
                    <?php if (empty($programs)): ?>
                    <div class="text-center py-5">
                        <i class="fas fa-graduation-cap fa-3x text-muted mb-3"></i>
                        <p class="text-muted">No programs available at this university yet.</p>
                        <a href="admin-create-program.php?university_id=<?= $university_id ?>" class="btn btn-primary">Add Your First Program</a>
                    </div>
                    <?php else: ?>
                    <?php foreach ($programs as $p): ?>
                    <div class="program-card">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <h4><?= htmlspecialchars($p['name']) ?></h4>
                                <span class="degree-badge degree-<?= $p['degree_level'] ?>">
                                    <?= htmlspecialchars($p['degree_level_display']) ?>
                                </span>
                            </div>
                            <div class="text-right">
                                <div class="fee-info">
                                    <strong>$<?= number_format($p['tuition_fee'], 2) ?></strong><br>
                                    per year
                                </div>
                            </div>
                        </div>
                        
                        <div class="mt-3">
                            <p class="text-muted"><?= substr(htmlspecialchars($p['program_description']), 0, 200) ?>...</p>
                            
                            <div class="d-flex justify-content-between">
                                <div>
                                    <small>Duration: <?= $p['duration_months'] ?> months</small>
                                </div>
                                <div>
                                    <small>Intakes: <?= htmlspecialchars(implode(', ', json_decode($p['intake_months'] ?? '[]', true) ?: [])) ?></small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mt-3">
                            <a href="admin-program-profile.php?id=<?= $p['id'] ?>" class="btn btn-primary btn-sm">View Details</a>
                            <a href="admin-edit-program.php?id=<?= $p['id'] ?>" class="btn btn-outline-primary btn-sm">Edit</a>
                            <button class="btn btn-danger btn-sm delete-program" data-id="<?= $p['id'] ?>">Delete</button>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <div class="col-lg-4">
            <!-- Stats -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>University Statistics</h5>
                </div>
                <div class="card-body">
                    <ul class="list-unstyled">
                        <li class="mb-3"><i class="fas fa-file-alt mr-2"></i> 
                            <strong>Total Applications:</strong><br>
                            <?= $stats['total_applications'] ?>
                        </li>
                        <li class="mb-3"><i class="fas fa-check-circle mr-2"></i> 
                            <strong>Accepted Applications:</strong><br>
                            <?= $stats['accepted_applications'] ?>
                        </li>
                        <li class="mb-3"><i class="fas fa-graduation-cap mr-2"></i> 
                            <strong>Students Placed:</strong><br>
                            <?= $stats['total_students'] ?>
                        </li>
                        <li class="mb-3"><i class="fas fa-award mr-2"></i> 
                            <strong>Scholarships Secured:</strong><br>
                            $<?= number_format($stats['total_scholarships'], 2) ?>
                        </li>
                    </ul>
                </div>
            </div>
            
            <!-- Quick Actions -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>Quick Actions</h5>
                </div>
                <div class="card-body">
                    <div class="d-flex flex-column">
                        <a href="admin-create-application.php?university_id=<?= $university_id ?>" class="btn btn-primary mb-2">
                            <i class="fas fa-file-alt"></i> Create Application
                        </a>
                        <a href="admin-create-program.php?university_id=<?= $university_id ?>" class="btn btn-primary mb-2">
                            <i class="fas fa-graduation-cap"></i> Add Program
                        </a>
                        <a href="admin-universities.php" class="btn btn-outline-primary">
                            <i class="fas fa-arrow-left"></i> Back to Universities
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</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>
    // Logo upload functionality
    document.getElementById('logoUpload').addEventListener('click', function() {
        document.getElementById('logoFile').click();
    });
    
    document.getElementById('logoFile').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            document.getElementById('logoUpload').innerHTML = `
                <i class="fas fa-file-alt fa-3x mb-3" style="color: #3fb7fe;"></i>
                <h6>${file.name}</h6>
                <p class="text-muted small">${(file.size / 1024 / 1024).toFixed(2)} MB</p>
                <p class="text-success">Ready to upload</p>
            `;
        }
    });
    
    // Form submission confirmation
    $('form').on('submit', function(e) {
        const universityName = $('input[name="name"]').val();
        
        if (universityName && confirm(`You are about to update the university "${universityName}". Continue?`)) {
            return true;
        } else {
            e.preventDefault();
        }
    });
    
    // Delete program confirmation
    $('.delete-program').on('click', function() {
        const programId = $(this).data('id');
        
        if (confirm('Are you sure you want to delete this program? This action cannot be undone.')) {
            // In a real application, this would make an AJAX call or redirect to a delete handler
            alert('In a real application, this would delete the program from the database.');
        }
    });
</script>
</body>
</html>