<?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/programs/';

// Create upload directory if it doesn't exist
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

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

// Handle program creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_program'])) {
    $university_id = $_POST['university_id'] ?? null;
    $name = trim($_POST['name'] ?? '');
    $degree_level = $_POST['degree_level'] ?? '';
    $duration_months = $_POST['duration_months'] ?? null;
    $tuition_fee = $_POST['tuition_fee'] ?? null;
    $tuition_fee_currency = $_POST['tuition_fee_currency'] ?? 'USD';
    $intake_months = $_POST['intake_months'] ?? [];
    $language_requirements = $_POST['language_requirements'] ?? '';
    $academic_requirements = $_POST['academic_requirements'] ?? '';
    $program_description = $_POST['program_description'] ?? '';
    $admission_deadline = $_POST['admission_deadline'] ?? null;
    $application_fee = $_POST['application_fee'] ?? null;
    
    // Validate form data
    if (!$university_id || empty($name) || empty($degree_level)) {
        $error = "University, program name, and degree level are required.";
    } elseif (!is_numeric($duration_months) || $duration_months <= 0) {
        $error = "Duration must be a positive number.";
    } elseif ($tuition_fee !== null && (!is_numeric($tuition_fee) || $tuition_fee < 0)) {
        $error = "Tuition fee must be zero or a positive number.";
    } else {
        try {
            // Start transaction
            $pdo->beginTransaction();
            
            // Create program
            $stmt = $pdo->prepare("INSERT INTO programs (
                university_id, name, degree_level, duration_months, tuition_fee, 
                tuition_fee_currency, intake_months, language_requirements, 
                academic_requirements, program_description, admission_deadline, 
                application_fee, created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
            
            $stmt->execute([
                $university_id, $name, $degree_level, $duration_months, $tuition_fee,
                $tuition_fee_currency, json_encode($intake_months), $language_requirements,
                $academic_requirements, $program_description, $admission_deadline,
                $application_fee
            ]);
            
            $program_id = $pdo->lastInsertId();
            
            // Handle brochure upload
            if (isset($_FILES['brochure']) && $_FILES['brochure']['name']) {
                $file_name = $_FILES['brochure']['name'];
                $file_tmp = $_FILES['brochure']['tmp_name'];
                $file_size = $_FILES['brochure']['size'];
                $file_error = $_FILES['brochure']['error'];
                
                if ($file_error === UPLOAD_ERR_OK && $file_size <= 10 * 1024 * 1024) {
                    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                    $allowed_exts = ['pdf', 'doc', 'docx'];
                    
                    if (in_array($file_ext, $allowed_exts)) {
                        $unique_name = $program_id . '_brochure_' . time() . '.' . $file_ext;
                        $file_path = $upload_dir . $unique_name;
                        
                        if (move_uploaded_file($file_tmp, $file_path)) {
                            // Update program with brochure path
                            $pdo->prepare("UPDATE programs SET brochure_path = ? WHERE id = ?")
                                ->execute([$file_path, $program_id]);
                        }
                    }
                }
            }
            
            // Log the activity
            $pdo->prepare("INSERT INTO activities (
                user_id, activity_type, description, created_at
            ) VALUES (?, ?, ?, NOW())")->execute([
                $_SESSION['user_id'],
                "program_created",
                "Admin {$_SESSION['first_name']} {$_SESSION['last_name']} created program {$name} for university {$university_id}"
            ]);
            
            // Commit transaction
            $pdo->commit();
            
            $success = "Program created successfully!";
            
            // Clear form on success if we want to create another
            $_POST = array();
            
        } catch (Exception $e) {
            $pdo->rollback();
            $error = "Failed to create program. Please try again. Error: " . $e->getMessage();
        }
    }
}

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Create Program - 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;
        }
        .form-section:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }
        .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;
        }
        .file-upload:hover {
            border-color: #3fb7fe;
            background: #f8f9fa;
        }
        .file-input {
            display: none;
        }
        .info-box {
            background: #f8f9fa;
            border-left: 4px solid #3fb7fe;
            padding: 15px;
            margin: 20px 0;
            border-radius: 5px;
        }
        .checkbox-group {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 10px;
        }
        .checkbox-item {
            margin-bottom: 10px;
        }
        .action-buttons {
            margin-top: 30px;
            margin-bottom: 20px;
        }
        .preview-image {
            max-width: 100%;
            max-height: 200px;
            margin-top: 10px;
            display: none;
        }
    </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 Program</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>
        <div class="text-center action-buttons">
            <a href="admin-programs.php" class="btn btn-primary mr-3">View All Programs</a>
            <a href="<?= $_SERVER['PHP_SELF'] ?>" class="btn btn-success">Create Another Program</a>
        </div>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data">
        <div class="form-section">
            <h5 class="section-title">Program Information</h5>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>University *</label>
                    <select name="university_id" class="form-control" required>
                        <option value="">Select University</option>
                        <?php foreach ($universities as $u): ?>
                        <option value="<?= $u['id'] ?>" <?= ($_POST['university_id'] ?? '') == $u['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($u['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6 mb-3">
                    <label>Program Name *</label>
                    <input type="text" name="name" class="form-control" 
                           value="<?= htmlspecialchars($_POST['name'] ?? '') ?>" required>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Degree Level *</label>
                    <select name="degree_level" class="form-control" required>
                        <option value="">Select Level</option>
                        <option value="diploma" <?= ($_POST['degree_level'] ?? '') === 'diploma' ? 'selected' : '' ?>>Diploma</option>
                        <option value="bachelors" <?= ($_POST['degree_level'] ?? '') === 'bachelors' ? 'selected' : '' ?>>Bachelor's</option>
                        <option value="masters" <?= ($_POST['degree_level'] ?? '') === 'masters' ? 'selected' : '' ?>>Master's</option>
                        <option value="phd" <?= ($_POST['degree_level'] ?? '') === 'phd' ? 'selected' : '' ?>>PhD</option>
                        <option value="certificate" <?= ($_POST['degree_level'] ?? '') === 'certificate' ? 'selected' : '' ?>>Certificate</option>
                    </select>
                </div>
                <div class="col-md-6 mb-3">
                    <label>Duration (months) *</label>
                    <input type="number" name="duration_months" class="form-control" min="1" 
                           value="<?= htmlspecialchars($_POST['duration_months'] ?? '') ?>" required>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Tuition Fee</label>
                    <div class="input-group">
                        <input type="number" name="tuition_fee" class="form-control" step="0.01" min="0"
                               value="<?= htmlspecialchars($_POST['tuition_fee'] ?? '') ?>">
                        <div class="input-group-append">
                            <select name="tuition_fee_currency" class="form-control">
                                <option value="USD" <?= ($_POST['tuition_fee_currency'] ?? 'USD') === 'USD' ? 'selected' : '' ?>>USD</option>
                                <option value="EUR" <?= ($_POST['tuition_fee_currency'] ?? 'USD') === 'EUR' ? 'selected' : '' ?>>EUR</option>
                                <option value="GBP" <?= ($_POST['tuition_fee_currency'] ?? 'USD') === 'GBP' ? 'selected' : '' ?>>GBP</option>
                                <option value="CAD" <?= ($_POST['tuition_fee_currency'] ?? 'USD') === 'CAD' ? 'selected' : '' ?>>CAD</option>
                                <option value="AUD" <?= ($_POST['tuition_fee_currency'] ?? 'USD') === 'AUD' ? 'selected' : '' ?>>AUD</option>
                            </select>
                        </div>
                    </div>
                </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($_POST['application_fee'] ?? '') ?>">
                    </div>
                </div>
            </div>
        </div>
        
        <div class="form-section">
            <h5 class="section-title">Admission Information</h5>
            <div class="form-group">
                <label>Intake Months *</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) ?>"
                                   <?= (isset($_POST['intake_months']) && in_array($month, $_POST['intake_months'])) ? 'checked' : '' ?>>
                            <label class="custom-control-label" for="<?= strtolower($month) ?>"><?= $month ?></label>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Admission Deadline</label>
                    <input type="date" name="admission_deadline" class="form-control" 
                           value="<?= htmlspecialchars($_POST['admission_deadline'] ?? '') ?>">
                </div>
            </div>
            <div class="form-group">
                <label>Language Requirements</label>
                <textarea name="language_requirements" class="form-control" rows="3" 
                          placeholder="e.g., IELTS 6.5, TOEFL iBT 90, etc."><?= htmlspecialchars($_POST['language_requirements'] ?? '') ?></textarea>
            </div>
            <div class="form-group">
                <label>Academic Requirements</label>
                <textarea name="academic_requirements" class="form-control" rows="3" 
                          placeholder="e.g., High school diploma with minimum 75%, etc."><?= htmlspecialchars($_POST['academic_requirements'] ?? '') ?></textarea>
            </div>
        </div>
        
        <div class="form-section">
            <h5 class="section-title">Program Details</h5>
            <div class="form-group">
                <label>Program Description *</label>
                <textarea name="program_description" class="form-control" rows="6" required 
                          placeholder="Provide a detailed description of the program, including curriculum, specializations, career opportunities, etc."><?= htmlspecialchars($_POST['program_description'] ?? '') ?></textarea>
            </div>
            
            <div class="form-group">
                <label>Program Brochure</label>
                <div class="file-upload" id="brochureUpload">
                    <i class="fas fa-file-upload fa-3x mb-3" style="color: #3fb7fe;"></i>
                    <h6>Upload Brochure</h6>
                    <p class="text-muted small">PDF, DOC, or DOCX (max 10MB)</p>
                    <input type="file" name="brochure" id="brochureFile" class="file-input" accept=".pdf,.doc,.docx">
                </div>
                <small class="form-text text-muted">Optional: Upload a brochure or detailed program information</small>
            </div>
        </div>
        
        <div class="info-box">
            <h6><i class="fas fa-info-circle"></i> What Happens Next?</h6>
            <ul class="small">
                <li>The program will be available for students to view and apply to</li>
                <li>You can edit program details at any time from the program profile page</li>
                <li>Students can search and filter programs based on these details</li>
                <li>Applications to this program can be managed from the applications section</li>
            </ul>
        </div>
        
        <div class="text-center action-buttons">
            <button type="submit" name="create_program" class="btn btn-primary btn-lg px-5">Create Program</button>
            <a href="admin-programs.php" class="btn btn-outline-secondary btn-lg ml-3">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() {
    // Brochure upload preview
    $('#brochureFile').change(function(e) {
        const file = e.target.files[0];
        if (file) {
            $('#brochureUpload').html(`
                <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 university = $('select[name="university_id"] option:selected').text();
        const programName = $('input[name="name"]').val();
        
        if (!university || !programName) {
            e.preventDefault();
            alert('Please fill in all required fields.');
            return false;
        }
        
        if (!confirm(`You are about to create the program "${programName}" at ${university}. Continue?`)) {
            e.preventDefault();
            return false;
        }
    });
    
    // Pre-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>