<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php');
    exit;
}

require_once 'connectiondb.php';

$errors = [];
$success_message = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// Handle create batch
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_batch'])) {
    $batch_name = trim($_POST['batch_name'] ?? '');
    $description = trim($_POST['description'] ?? '');

    if (empty($batch_name)) {
        $errors[] = "Batch name is required.";
    }

    if (empty($errors)) {
        $stmt = $pdo->prepare("INSERT INTO batches (batch_name, description) VALUES (?, ?)");
        if ($stmt->execute([$batch_name, $description])) {
            $success_message = "Batch created successfully.";
        } else {
            $errors[] = "Failed to create batch.";
        }
    }
}

// Handle delete batch
if (isset($_GET['delete_batch_id'])) {
    $delete_batch_id = intval($_GET['delete_batch_id']);
    $stmt = $pdo->prepare("DELETE FROM batches WHERE id = ?");
    if ($stmt->execute([$delete_batch_id])) {
        $success_message = "Batch deleted successfully.";
    } else {
        $errors[] = "Failed to delete batch.";
    }
}

// Fetch all batches
$stmt = $pdo->query("SELECT * FROM batches ORDER BY created_at DESC");
$batches = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Admin - Manage Batches</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<?php include 'navbar.php'; ?>
<div class="container my-4">
    <h2>Manage Batches</h2>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger">
            <ul>
                <?php foreach ($errors as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <?php if ($success_message): ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($success_message); ?></div>
    <?php endif; ?>

    <form method="POST" action="admin_batches.php" class="mb-4">
        <div class="mb-3">
            <label for="batch_name" class="form-label">Batch Name</label>
            <input type="text" name="batch_name" id="batch_name" class="form-control" required />
        </div>
        <div class="mb-3">
            <label for="description" class="form-label">Description (optional)</label>
            <textarea name="description" id="description" class="form-control" rows="3"></textarea>
        </div>
        <button type="submit" name="create_batch" class="btn btn-primary">Create Batch</button>
    </form>

    <?php if (empty($batches)): ?>
        <p>No batches found.</p>
    <?php else: ?>
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Batch Name</th>
                    <th>Description</th>
                    <th>Created At</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($batches as $batch): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($batch['id']); ?></td>
                        <td><?php echo htmlspecialchars($batch['batch_name']); ?></td>
                        <td><?php echo nl2br(htmlspecialchars($batch['description'])); ?></td>
                        <td><?php echo htmlspecialchars($batch['created_at']); ?></td>
                        <td>
                            <a href="admin_batches.php?delete_batch_id=<?php echo $batch['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this batch?');">Delete</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
