<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], ['super_admin', 'system_admin'])) {
    header("Location: login.php");
    exit();
}

include '../includes/db.php';
include 'includes/header.php';

$message = "";

// Generate bulk voucher codes
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['generate_bulk'])) {
    $count = intval($_POST['bulk_count']);
    $generated_codes = [];
    
    for ($i = 0; $i < $count; $i++) {
        // Generate unique voucher code
        $voucher_code = 'VC' . strtoupper(uniqid()) . rand(100, 999);
        
        // Insert voucher code without student/program assignment (for prospectus distribution)
        $sql = "INSERT INTO voucher_codes (code, generated_by, status) 
                VALUES ('$voucher_code', {$_SESSION['user_id']}, 'active')";
        
        if ($conn->query($sql) === TRUE) {
            $generated_codes[] = $voucher_code;
        }
    }
    
    if (!empty($generated_codes)) {
        $message = "Successfully generated " . count($generated_codes) . " voucher codes!";
    } else {
        $message = "Error generating voucher codes.";
    }
}

// Generate voucher code
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['generate_voucher'])) {
    $student_id = intval($_POST['student_id']);
    $program_id = intval($_POST['program_id']);
    
    // Generate unique voucher code
    $voucher_code = 'VC' . strtoupper(uniqid()) . rand(100, 999);
    
    // Check if voucher already exists for this student and program
    $check_sql = "SELECT id FROM voucher_codes WHERE student_id = $student_id AND program_id = $program_id AND status = 'active'";
    $check_result = $conn->query($check_sql);
    
    if ($check_result->num_rows > 0) {
        $message = "An active voucher already exists for this student and program.";
    } else {
        // Insert new voucher code
        $expires_at = date('Y-m-d H:i:s', strtotime('+7 days')); // Expire in 7 days
        $sql = "INSERT INTO voucher_codes (code, student_id, program_id, generated_by, expires_at) 
                VALUES ('$voucher_code', $student_id, $program_id, {$_SESSION['user_id']}, '$expires_at')";
        
        if ($conn->query($sql) === TRUE) {
            $message = "Voucher code generated successfully: $voucher_code";
        } else {
            $message = "Error generating voucher code: " . $conn->error;
        }
    }
}

// Get all students
$students_sql = "SELECT id, full_name, email FROM users WHERE role = 'student' ORDER BY full_name";
$students_result = $conn->query($students_sql);

// Get all programs
$programs_sql = "SELECT id, program_name FROM programs ORDER BY program_name";
$programs_result = $conn->query($programs_sql);

// Get voucher codes (updated to handle NULL student_id and program_id)
$vouchers_sql = "SELECT vc.*, 
                COALESCE(u.full_name, 'Unassigned') as student_name, 
                COALESCE(p.program_name, 'Unassigned') as program_name, 
                a.full_name as generated_by_name 
                FROM voucher_codes vc
                LEFT JOIN users u ON vc.student_id = u.id
                LEFT JOIN programs p ON vc.program_id = p.id
                JOIN users a ON vc.generated_by = a.id
                ORDER BY vc.generated_at DESC";
$vouchers_result = $conn->query($vouchers_sql);
?>

<div class="dashboard-container">
    <div class="sidebar admin-sidebar">
        <?php include 'includes/sidebar.php'; ?>
    </div>

    <div class="main-content">
        <h2>Voucher Management</h2>
        
        <?php if($message): ?>
            <div class="alert alert-info">
                <?php echo $message; ?>
            </div>
        <?php endif; ?>

        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Generate Bulk Voucher Codes</h3>
            </div>
            <div class="card-body">
                <form method="POST" action="">
                    <div class="form-group">
                        <label>Number of Voucher Codes to Generate</label>
                        <input type="number" name="bulk_count" class="form-control" min="1" max="1000" value="10" required>
                        <small>Generate voucher codes that can be used by any student for any program. These will be distributed with prospectus.</small>
                    </div>
                    <button type="submit" name="generate_bulk" class="btn-primary">Generate Bulk Voucher Codes</button>
                </form>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Generate Specific Voucher Code</h3>
            </div>
            <div class="card-body">
                <form method="POST" action="">
                    <div class="form-group">
                        <label>Select Student</label>
                        <select name="student_id" class="form-control" required>
                            <option value="">-- Select Student --</option>
                            <?php while($student = $students_result->fetch_assoc()): ?>
                                <option value="<?php echo $student['id']; ?>">
                                    <?php echo $student['full_name'] . ' (' . $student['email'] . ')'; ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Select Program</label>
                        <select name="program_id" class="form-control" required>
                            <option value="">-- Select Program --</option>
                            <?php while($program = $programs_result->fetch_assoc()): ?>
                                <option value="<?php echo $program['id']; ?>">
                                    <?php echo $program['program_name']; ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <button type="submit" name="generate_voucher" class="btn-primary">Generate Voucher Code</button>
                </form>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Generated Voucher Codes</h3>
            </div>
            <div class="card-body">
                <table>
                    <thead>
                        <tr>
                            <th>Voucher Code</th>
                            <th>Student</th>
                            <th>Program</th>
                            <th>Status</th>
                            <th>Generated At</th>
                            <th>Expires At</th>
                            <th>Generated By</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if($vouchers_result->num_rows > 0): ?>
                            <?php while($voucher = $vouchers_result->fetch_assoc()): ?>
                                <tr>
                                    <td><strong><?php echo $voucher['code']; ?></strong></td>
                                    <td><?php echo $voucher['student_name']; ?></td>
                                    <td><?php echo $voucher['program_name']; ?></td>
                                    <td>
                                        <?php
                                        $status_class = '';
                                        switch($voucher['status']) {
                                            case 'active':
                                                $status_class = 'badge-success';
                                                break;
                                            case 'used':
                                                $status_class = 'badge-info';
                                                break;
                                            case 'expired':
                                                $status_class = 'badge-danger';
                                                break;
                                        }
                                        ?>
                                        <span class="badge <?php echo $status_class; ?>">
                                            <?php echo ucfirst($voucher['status']); ?>
                                        </span>
                                    </td>
                                    <td><?php echo date('M d, Y H:i', strtotime($voucher['generated_at'])); ?></td>
                                    <td>
                                        <?php 
                                        if($voucher['expires_at']) {
                                            echo date('M d, Y H:i', strtotime($voucher['expires_at']));
                                        } else {
                                            echo 'N/A';
                                        }
                                        ?>
                                    </td>
                                    <td><?php echo $voucher['generated_by_name']; ?></td>
                                    <td>
                                        <?php if($voucher['status'] == 'active'): ?>
                                            <a href="?action=expire&id=<?php echo $voucher['id']; ?>" 
                                               class="btn-danger" style="padding: 5px 10px; font-size: 0.9rem;"
                                               onclick="return confirm('Are you sure you want to expire this voucher?')">Expire</a>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="8" style="text-align: center;">No voucher codes generated yet.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php
// Handle voucher expiration
if(isset($_GET['action']) && $_GET['action'] == 'expire' && isset($_GET['id'])) {
    $voucher_id = intval($_GET['id']);
    $sql = "UPDATE voucher_codes SET status = 'expired' WHERE id = $voucher_id";
    $conn->query($sql);
    header("Location: voucher_management_fixed.php");
    exit();
}

include 'includes/footer.php';
?>
