
<?php
// batch_details.php
// This page displays the detailed information for a specific batch and allows editing for authorized users.

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header("Location: index.php?page=login");
    exit();
}

require_once 'config/database.php';

$batch = null;
$message = '';
$is_error = false;
$user_role = $_SESSION['user_role'] ?? 'guest';
$batch_id = $_GET['id'] ?? null;

// Handle form submission for editing batch details
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($user_role === 'admin' || $user_role === 'instructor')) {
    $batch_id_post = $_POST['batch_id'] ?? null;
    $batch_name = trim($_POST['batch_name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $fees = $_POST['fees'] ?? null;
    $start_date = $_POST['start_date'] ?? null;
    $end_date = $_POST['end_date'] ?? null;

    if (!$batch_id_post || empty($batch_name) || empty($fees) || empty($start_date) || empty($end_date)) {
        $message = "All required fields must be filled out.";
        $is_error = true;
    } else {
        try {
            $stmt = $pdo->prepare("UPDATE batches SET batch_name = ?, description = ?, fees = ?, start_date = ?, end_date = ? WHERE id = ?");
            $stmt->execute([$batch_name, $description, $fees, $start_date, $end_date, $batch_id_post]);
            $message = "Batch details updated successfully!";
            // Redirect to the same page with a success message to prevent resubmission
            header("Location: index.php?page=batch_details&id=" . urlencode($batch_id_post) . "&success=" . urlencode($message));
            exit();
        } catch (PDOException $e) {
            $message = "Database error: " . $e->getMessage();
            $is_error = true;
        }
    }
}

// Fetch batch details
if (!$batch_id || !is_numeric($batch_id)) {
    $message = "Invalid batch ID provided.";
    $is_error = true;
} else {
    try {
        $sql = "
            SELECT
                b.id,
                b.batch_name,
                b.description,
                b.fees,
                b.duration,
                b.start_date,
                b.end_date,
                b.modality,
                c.course_name,
                u.full_name AS instructor_name
            FROM batches b
            LEFT JOIN courses c ON b.course_id = c.id
            LEFT JOIN users u ON b.instructor_id = u.id
            WHERE b.id = ? LIMIT 1
        ";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$batch_id]);
        $batch = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$batch) {
            $message = "Batch not found.";
            $is_error = true;
        }
    } catch (PDOException $e) {
        $message = "Database error fetching batch details: " . $e->getMessage();
        $is_error = true;
        error_log("Batch Details Fetch Error: " . $e->getMessage());
    }
}

// Check for success message in URL
if (isset($_GET['success'])) {
    $message = htmlspecialchars($_GET['success']);
    $is_error = false;
}
?>

<div class="w-full max-w-4xl mx-auto p-6 bg-white rounded-lg shadow-xl">

    <?php if ($is_error || !$batch): ?>
        <div class="mb-6 p-4 rounded-md text-center text-lg bg-red-100 text-red-700 border border-red-200">
            <?php echo $message; ?>
            <p class="mt-4"><a href="index.php?page=manage_batches" class="text-blue-600 hover:underline">Back to Batches</a></p>
        </div>
    <?php else: ?>
        <?php if (!empty($message)): ?>
            <div class="mb-4 p-4 rounded-md text-sm <?php echo $is_error ? 'bg-red-100 text-red-700' : 'bg-green-100 text-green-700'; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>

        <div id="batchView" class="space-y-6">
            <div class="flex justify-between items-start mb-6 pb-4 border-b border-gray-200">
                <h1 class="text-3xl font-extrabold text-gray-900 leading-tight">
                    Batch Details
                    <span class="block mt-1 text-lg font-normal text-gray-600">for <?php echo htmlspecialchars($batch['batch_name']); ?></span>
                </h1>
                <?php if ($user_role === 'admin' || $user_role === 'instructor'): ?>
                    <button id="editButton" class="px-4 py-2 bg-yellow-500 text-white font-semibold rounded-md hover:bg-yellow-600 transition duration-300">
                        Edit Details
                    </button>
                <?php endif; ?>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="flex items-center text-lg text-gray-700"><span class="font-semibold">Course:</span> <span class="ml-2"><?php echo htmlspecialchars($batch['course_name']); ?></span></div>
                <div class="flex items-center text-lg text-gray-700"><span class="font-semibold">Instructor:</span> <span class="ml-2"><?php echo htmlspecialchars($batch['instructor_name'] ?: 'N/A'); ?></span></div>
                <div class="flex items-center text-lg text-gray-700"><span class="font-semibold">Fees:</span> <span class="ml-2">$<?php echo number_format($batch['fees'], 2); ?></span></div>
                <div class="flex items-center text-lg text-gray-700"><span class="font-semibold">Modality:</span> <span class="ml-2 capitalize"><?php echo htmlspecialchars($batch['modality']); ?></span></div>
                <div class="flex items-center text-lg text-gray-700"><span class="font-semibold">Start Date:</span> <span class="ml-2"><?php echo date('M d, Y', strtotime($batch['start_date'])); ?></span></div>
                <div class="flex items-center text-lg text-gray-700"><span class="font-semibold">End Date:</span> <span class="ml-2"><?php echo date('M d, Y', strtotime($batch['end_date'])); ?></span></div>
            </div>

            <div class="pt-6 border-t border-gray-200">
                <h3 class="text-xl font-bold text-gray-800 mb-2">Description</h3>
                <p class="text-gray-700 leading-relaxed"><?php echo nl2br(htmlspecialchars($batch['description'])); ?></p>
            </div>
        </div>

        <div id="batchEditForm" class="hidden space-y-6">
            <div class="flex justify-between items-start mb-6 pb-4 border-b border-gray-200">
                <h1 class="text-3xl font-extrabold text-gray-900 leading-tight">Edit Batch Details</h1>
                <button id="cancelEditButton" class="px-4 py-2 bg-gray-200 text-gray-700 font-semibold rounded-md hover:bg-gray-300 transition duration-300">
                    Cancel
                </button>
            </div>
            
            <form action="index.php?page=batch_details&id=<?php echo htmlspecialchars($batch['id']); ?>" method="POST" class="space-y-6">
                <input type="hidden" name="batch_id" value="<?php echo htmlspecialchars($batch['id']); ?>">

                <div>
                    <label for="batch_name" class="block text-sm font-medium text-gray-700">Batch Name</label>
                    <input type="text" name="batch_name" id="batch_name" value="<?php echo htmlspecialchars($batch['batch_name']); ?>" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm">
                </div>
                
                <div>
                    <label for="description" class="block text-sm font-medium text-gray-700">Description</label>
                    <textarea name="description" id="description" rows="4" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm"><?php echo htmlspecialchars($batch['description']); ?></textarea>
                </div>

                <div>
                    <label for="fees" class="block text-sm font-medium text-gray-700">Fees ($)</label>
                    <input type="number" name="fees" id="fees" value="<?php echo htmlspecialchars($batch['fees']); ?>" required step="0.01" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm">
                </div>
                
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
                    <div>
                        <label for="start_date" class="block text-sm font-medium text-gray-700">Start Date</label>
                        <input type="date" name="start_date" id="start_date" value="<?php echo htmlspecialchars($batch['start_date']); ?>" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm">
                    </div>
                    <div>
                        <label for="end_date" class="block text-sm font-medium text-gray-700">End Date</label>
                        <input type="date" name="end_date" id="end_date" value="<?php echo htmlspecialchars($batch['end_date']); ?>" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm">
                    </div>
                </div>

                <div class="flex justify-end mt-6">
                    <button type="submit" class="px-6 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition duration-300">
                        Update Batch
                    </button>
                </div>
            </form>
        </div>
    <?php endif; ?>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const editButton = document.getElementById('editButton');
        const cancelButton = document.getElementById('cancelEditButton');
        const batchView = document.getElementById('batchView');
        const batchEditForm = document.getElementById('batchEditForm');

        if (editButton && cancelButton && batchView && batchEditForm) {
            editButton.addEventListener('click', function() {
                batchView.classList.add('hidden');
                batchEditForm.classList.remove('hidden');
            });

            cancelButton.addEventListener('click', function() {
                batchView.classList.remove('hidden');
                batchEditForm.classList.add('hidden');
            });
        }
    });
</script>