<?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 programs with filtering
$university_filter = $_GET['university'] ?? '';
$level_filter = $_GET['level'] ?? '';
$search = $_GET['search'] ?? '';

// Build query
$sql = "SELECT p.*, u.name as university_name, u.logo as university_logo, u.country_id,
        c.name as country_name, c.flag_path as country_flag
        FROM programs p
        JOIN universities u ON p.university_id = u.id
        JOIN countries c ON u.country_id = c.id";

$conditions = [];
$params = [];

if ($university_filter) {
    $conditions[] = "p.university_id = ?";
    $params[] = $university_filter;
}

if ($level_filter) {
    $conditions[] = "p.degree_level = ?";
    $params[] = $level_filter;
}

if ($search) {
    $conditions[] = "(p.name LIKE ? OR u.name LIKE ? OR p.program_description LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($conditions) {
    $sql .= " WHERE " . implode(" AND ", $conditions);
}

$sql .= " ORDER BY p.created_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$programs = $stmt->fetchAll();

// Get stats
$stats = [
    'total' => $pdo->query("SELECT COUNT(*) FROM programs")->fetchColumn(),
    'diploma' => $pdo->query("SELECT COUNT(*) FROM programs WHERE degree_level = 'diploma'")->fetchColumn(),
    'bachelors' => $pdo->query("SELECT COUNT(*) FROM programs WHERE degree_level = 'bachelors'")->fetchColumn(),
    'masters' => $pdo->query("SELECT COUNT(*) FROM programs WHERE degree_level = 'masters'")->fetchColumn(),
    'phd' => $pdo->query("SELECT COUNT(*) FROM programs WHERE degree_level = 'phd'")->fetchColumn(),
];

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

// Handle program deletion
if (isset($_GET['delete']) && !empty($_GET['delete'])) {
    $program_id = $_GET['delete'];
    
    try {
        // Start transaction
        $pdo->beginTransaction();
        
        // Delete the program
        $stmt = $pdo->prepare("DELETE FROM programs WHERE id = ?");
        $stmt->execute([$program_id]);
        
        // Log the activity
        $pdo->prepare("INSERT INTO activities (
            user_id, activity_type, description, created_at
        ) VALUES (?, ?, ?, NOW())")->execute([
            $_SESSION['user_id'],
            "program_deleted",
            "Admin {$_SESSION['first_name']} {$_SESSION['last_name']} deleted program with ID: {$program_id}"
        ]);
        
        // Commit transaction
        $pdo->commit();
        
        // Redirect to avoid resubmission
        header("Location: admin-programs.php?deleted=1");
        exit;
    } catch (Exception $e) {
        $pdo->rollback();
        $error = "Failed to delete program. 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>Programs - 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>
        .stat-card {
            border-left: 5px solid #3fb7fe;
            margin-bottom: 20px;
            transition: all 0.3s ease;
        }
        .stat-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .university-logo {
            height: 60px;
            width: 60px;
            object-fit: contain;
            background: white;
            padding: 5px;
            border-radius: 5px;
            border: 1px solid #eee;
        }
        .level-badge {
            font-size: 0.9em;
            padding: 3px 8px;
            border-radius: 15px;
            font-weight: 600;
        }
        .level-diploma {
            background: #fff3cd;
            color: #856404;
        }
        .level-bachelors {
            background: #d1ecf1;
            color: #0c5460;
        }
        .level-masters {
            background: #d4edda;
            color: #155724;
        }
        .level-phd {
            background: #f8d7da;
            color: #721c24;
        }
        .country-flag {
            width: 30px;
            height: 20px;
            object-fit: cover;
            border-radius: 3px;
            margin-right: 10px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .fee-info {
            font-size: 0.9em;
            color: #6c757d;
        }
        .program-card {
            transition: all 0.3s ease;
            height: 100%;
        }
        .program-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        .program-description {
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .search-box {
            position: relative;
        }
        .search-box .form-control {
            padding-left: 40px;
        }
        .search-box i {
            position: absolute;
            left: 15px;
            top: 12px;
            color: #6c757d;
        }
    </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">Manage Programs</h1>
    </div>

    <?php if (isset($_GET['deleted'])): ?>
        <div class="alert alert-success alert-dismissible fade show">
            Program deleted successfully!
            <button type="button" class="close" data-dismiss="alert">
                <span>&times;</span>
            </button>
        </div>
    <?php endif; ?>
    
    <?php if (isset($error)): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <?= htmlspecialchars($error) ?>
            <button type="button" class="close" data-dismiss="alert">
                <span>&times;</span>
            </button>
        </div>
    <?php endif; ?>

    <!-- Search and Filter -->
    <div class="row mb-4">
        <div class="col-lg-8">
            <form method="GET" class="d-flex">
                <div class="search-box flex-grow-1 mr-2">
                    <i class="fas fa-search"></i>
                    <input type="text" name="search" class="form-control" placeholder="Search by program, university, or description" 
                           value="<?= htmlspecialchars($search) ?>">
                </div>
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-search mr-1"></i> Search
                </button>
            </form>
        </div>
        <div class="col-lg-4">
            <div class="row">
                <div class="col-md-6 mb-2">
                    <select name="university" class="form-control" onchange="window.location='admin-programs.php?university='+this.value<?= $level_filter ? '&level='.urlencode($level_filter) : '' ?><?= $search ? '&search='.urlencode($search) : '' ?>">
                        <option value="">All Universities</option>
                        <?php foreach ($universities as $u): ?>
                        <option value="<?= $u['id'] ?>" <?= $university_filter == $u['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($u['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6 mb-2">
                    <select name="level" class="form-control" onchange="window.location='admin-programs.php<?= $university_filter ? '&university='.urlencode($university_filter) : '' ?>&level='+this.value<?= $search ? '&search='.urlencode($search) : '' ?>">
                        <option value="">All Levels</option>
                        <option value="diploma" <?= $level_filter === 'diploma' ? 'selected' : '' ?>>Diploma</option>
                        <option value="bachelors" <?= $level_filter === 'bachelors' ? 'selected' : '' ?>>Bachelor's</option>
                        <option value="masters" <?= $level_filter === 'masters' ? 'selected' : '' ?>>Master's</option>
                        <option value="phd" <?= $level_filter === 'phd' ? 'selected' : '' ?>>PhD</option>
                    </select>
                </div>
            </div>
        </div>
    </div>

    <!-- Stats -->
    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="stat-card">
                <div class="card-body">
                    <h6>Total Programs</h6>
                    <h3><?= $stats['total'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="stat-card" style="border-left-color: #ffc107;">
                <div class="card-body">
                    <h6>Diploma</h6>
                    <h3><?= $stats['diploma'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="stat-card" style="border-left-color: #007bff;">
                <div class="card-body">
                    <h6>Bachelor's</h6>
                    <h3><?= $stats['bachelors'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="stat-card" style="border-left-color: #28a745;">
                <div class="card-body">
                    <h6>Master's</h6>
                    <h3><?= $stats['masters'] ?></h3>
                </div>
            </div>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="stat-card" style="border-left-color: #dc3545;">
                <div class="card-body">
                    <h6>PhD</h6>
                    <h3><?= $stats['phd'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-9 mb-3">
            <div class="text-right">
                <a href="admin-create-program.php" class="btn btn-primary btn-lg">
                    <i class="fas fa-plus mr-2"></i> Create New Program
                </a>
            </div>
        </div>
    </div>

    <!-- Programs List -->
    <div class="row">
        <?php if (empty($programs)): ?>
        <div class="col-12">
            <div class="bg-light p-5 text-center rounded">
                <i class="fas fa-graduation-cap fa-3x text-muted mb-3"></i>
                <h5>No programs found</h5>
                <p class="text-muted">No programs match your search criteria.</p>
                <a href="admin-create-program.php" class="btn btn-primary mt-3">
                    <i class="fas fa-plus mr-2"></i> Create Your First Program
                </a>
            </div>
        </div>
        <?php else: ?>
        <?php foreach ($programs as $p): ?>
        <div class="col-lg-6 mb-4">
            <div class="card h-100 program-card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div class="d-flex align-items-center">
                            <img src="<?= htmlspecialchars($p['university_logo'] ?: 'img/university-placeholder.png') ?>" 
                                 alt="<?= htmlspecialchars($p['university_name']) ?>" class="university-logo mr-3">
                            <div>
                                <h5 class="mb-1"><?= htmlspecialchars($p['name']) ?></h5>
                                <div class="d-flex align-items-center">
                                    <?php if ($p['country_flag']): ?>
                                    <img src="<?= htmlspecialchars($p['country_flag']) ?>" 
                                         alt="<?= htmlspecialchars($p['country_name']) ?>" class="country-flag">
                                    <?php endif; ?>
                                    <small class="text-muted"><?= htmlspecialchars($p['country_name']) ?></small>
                                </div>
                            </div>
                        </div>
                        <span class="level-badge level-<?= $p['degree_level'] ?>">
                            <?= ucfirst($p['degree_level']) ?>
                        </span>
                    </div>
                    
                    <div class="mt-3">
                        <p class="text-muted mb-2 program-description">
                            <?= !empty($p['program_description']) ? 
                                htmlspecialchars($p['program_description']) : 
                                'No description available' ?>
                        </p>
                        
                        <div class="d-flex justify-content-between">
                            <div>
                                <strong><?= htmlspecialchars($p['university_name']) ?></strong>
                            </div>
                            <div class="fee-info">
                                <strong><?= $p['tuition_fee_currency'] ?> <?= number_format($p['tuition_fee'], 2) ?></strong><br>
                                per year
                            </div>
                        </div>
                        
                        <div class="mt-2">
                            <div class="d-flex justify-content-between">
                                <small class="text-muted">Duration: <?= $p['duration_months'] ?> months</small>
                                <small class="text-muted">
                                    Intakes: 
                                    <?php 
                                    $intakes = json_decode($p['intake_months'] ?? '[]', true);
                                    echo $intakes ? implode(', ', $intakes) : 'Not specified';
                                    ?>
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-footer bg-white">
                    <div class="d-flex justify-content-between">
                        <a href="admin-program-profile.php?id=<?= $p['id'] ?>" class="btn btn-sm btn-primary">
                            <i class="fas fa-eye mr-1"></i> View Details
                        </a>
                        <div class="btn-group">
                            <a href="admin-university-profile.php?id=<?= $p['university_id'] ?>" class="btn btn-sm btn-outline-primary">
                                <i class="fas fa-university mr-1"></i> University
                            </a>
                            <button class="btn btn-sm btn-danger delete-program" data-id="<?= $p['id'] ?>">
                                <i class="fas fa-trash mr-1"></i> Delete
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>
    </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>
    $(document).ready(function() {
        // Delete program confirmation
        $('.delete-program').on('click', function() {
            const programId = $(this).data('id');
            const programName = $(this).closest('.card-body').find('h5').text();
            
            if (confirm(`Are you sure you want to delete "${programName}"? This action cannot be undone.`)) {
                window.location.href = 'admin-programs.php?delete=' + programId;
            }
        });

        // Auto focus search input
        $('input[name="search"]').focus();
    });
</script>
</body>
</html>