<?php
declare(strict_types=1);
session_start();
require_once 'db/config.php';

// Security check: only administrators can access this page
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'administrator') {
    header('Location: login.php');
    exit;
}

$errors = [];
$messages = [];

if (isset($_GET['deleted']) && $_GET['deleted'] === 'true') {
    $messages[] = 'Horse deleted successfully!';
}

if (isset($_GET['edited']) && $_GET['edited'] === 'true') {
    $messages[] = 'Horse updated successfully!';
}


// Handle Add Horse
if (isset($_POST['action']) && $_POST['action'] === 'add_horse') {
    $name = $_POST['name'] ?? '';
    $breed = $_POST['breed'] ?? '';
    $description = $_POST['description'] ?? '';
    $image_url = $_POST['image_url'] ?? '';

    if (empty($name) || empty($breed)) {
        $errors[] = 'Name and Breed are required.';
    } else {
        try {
            $pdo = db();
            $stmt = $pdo->prepare('INSERT INTO horses (name, breed, description, image_url) VALUES (?, ?, ?, ?)');
            $stmt->execute([$name, $breed, $description, $image_url]);
            $messages[] = 'Horse added successfully!';
        } catch (PDOException $e) {
            $errors[] = 'Database error: ' . $e->getMessage();
        }
    }
}

// Handle Delete Horse
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    $id = $_GET['id'];
    try {
        $pdo = db();
        $stmt = $pdo->prepare('DELETE FROM horses WHERE id = ?');
        $stmt->execute([$id]);
        header('Location: admin_horses.php?deleted=true');
        exit;
    } catch (PDOException $e) {
        $errors[] = 'Database error: ' . $e->getMessage();
    }
}

// Fetch all horses
$horses = [];
try {
    $pdo = db();
    $stmt = $pdo->query('SELECT * FROM horses ORDER BY name');
    $horses = $stmt->fetchAll();
} catch (PDOException $e) {
    $errors[] = 'Database error: ' . $e->getMessage();
}

?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Admin: Manage Horses</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1>Manage Horses</h1>
        <a href="index.php" class="btn btn-info">&larr; Home</a>
    </div>

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

    <?php if (!empty($messages)): ?>
        <div class="alert alert-success">
            <?php foreach ($messages as $message): ?>
                <p class="mb-0"><?= htmlspecialchars($message) ?></p>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <div class="card mb-4">
        <div class="card-header">Add New Horse</div>
        <div class="card-body">
            <form action="admin_horses.php" method="post">
                <input type="hidden" name="action" value="add_horse">
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label for="name">Name</label>
                        <input type="text" class="form-control" id="name" name="name" required>
                    </div>
                    <div class="form-group col-md-6">
                        <label for="breed">Breed</label>
                        <input type="text" class="form-control" id="breed" name="breed" required>
                    </div>
                </div>
                <div class="form-group">
                    <label for="description">Description</label>
                    <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                </div>
                <div class="form-group">
                    <label for="image_url">Image URL</label>
                    <input type="text" class="form-control" id="image_url" name="image_url">
                </div>
                <button type="submit" class="btn btn-primary">Add Horse</button>
            </form>
        </div>
    </div>

    <div class="card">
        <div class="card-header">Existing Horses</div>
        <div class="card-body">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Breed</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($horses as $horse): ?>
                    <tr>
                        <td><?= htmlspecialchars($horse['name']) ?></td>
                        <td><?= htmlspecialchars($horse['breed']) ?></td>
                        <td>
                            <a href="edit_horse.php?id=<?= $horse['id'] ?>" class="btn btn-sm btn-warning">Edit</a>
                            <a href="admin_horses.php?action=delete&id=<?= $horse['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure?')">Delete</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

</div>
</body>
</html>
