<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/admin_auth.php';
require_once __DIR__ . '/../includes/admin_layout_top.php';

if (!isset($mysqli) && isset($conn)) {
    $mysqli = $conn;
}

function h($v): string {
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
}

$msg = '';
$err = '';

$mysqli->query("
CREATE TABLE IF NOT EXISTS lms_admin_planner (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    planner_date DATE NULL,
    planner_time TIME NULL,
    type VARCHAR(50) DEFAULT 'task',
    status VARCHAR(50) DEFAULT 'pending',
    notes TEXT NULL,
    created_by INT NULL,
    created_at DATETIME NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'create') {
        $title = trim($_POST['title'] ?? '');
        $date = trim($_POST['planner_date'] ?? '');
        $time = trim($_POST['planner_time'] ?? '');
        $type = trim($_POST['type'] ?? 'task');
        $notes = trim($_POST['notes'] ?? '');
        $adminId = (int)($GLOBALS['ADMIN_ID'] ?? 0);

        if ($title === '') {
            $err = 'Title is required.';
        } else {
            $stmt = $mysqli->prepare("
                INSERT INTO lms_admin_planner
                (title, planner_date, planner_time, type, status, notes, created_by, created_at)
                VALUES (?, ?, ?, ?, 'pending', ?, ?, NOW())
            ");
            $stmt->bind_param('sssssi', $title, $date, $time, $type, $notes, $adminId);

            if ($stmt->execute()) {
                $msg = 'Planner item added successfully.';
            } else {
                $err = 'Planner item add failed.';
            }
            $stmt->close();
        }
    }

    if ($action === 'done') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id > 0) {
            $stmt = $mysqli->prepare("UPDATE lms_admin_planner SET status='completed' WHERE id=? LIMIT 1");
            $stmt->bind_param('i', $id);
            if ($stmt->execute()) {
                $msg = 'Planner item completed.';
            }
            $stmt->close();
        }
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id > 0) {
            $stmt = $mysqli->prepare("DELETE FROM lms_admin_planner WHERE id=? LIMIT 1");
            $stmt->bind_param('i', $id);
            if ($stmt->execute()) {
                $msg = 'Planner item deleted.';
            }
            $stmt->close();
        }
    }
}

$rows = [];
$res = $mysqli->query("
    SELECT *
    FROM lms_admin_planner
    ORDER BY 
        CASE WHEN planner_date IS NULL THEN 1 ELSE 0 END,
        planner_date ASC,
        planner_time ASC,
        id DESC
");
if ($res) {
    $rows = $res->fetch_all(MYSQLI_ASSOC);
}
?>

<div class="container-fluid">
    <div class="d-flex flex-wrap justify-content-between align-items-center mb-4 gap-2">
        <div>
            <h4 class="mb-1">Planner</h4>
            <div class="text-muted small">Manage admin tasks, academic reminders and release plans.</div>
        </div>
        <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#plannerModal">
            <i class="bi bi-plus-circle me-1"></i> Add Plan
        </button>
    </div>

    <?php if ($msg): ?>
        <div class="alert alert-success"><?= h($msg) ?></div>
    <?php endif; ?>

    <?php if ($err): ?>
        <div class="alert alert-danger"><?= h($err) ?></div>
    <?php endif; ?>

    <div class="card border-0 shadow-sm">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table align-middle table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>Date</th>
                            <th>Title</th>
                            <th>Type</th>
                            <th>Status</th>
                            <th>Notes</th>
                            <th class="text-end">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!$rows): ?>
                            <tr>
                                <td colspan="6" class="text-center text-muted py-4">No planner items found.</td>
                            </tr>
                        <?php endif; ?>

                        <?php foreach ($rows as $r): ?>
                            <?php
                                $status = strtolower((string)($r['status'] ?? 'pending'));
                                $badge = $status === 'completed' ? 'bg-success' : 'bg-warning text-dark';
                            ?>
                            <tr>
                                <td>
                                    <div class="fw-semibold"><?= h($r['planner_date'] ?: '-') ?></div>
                                    <div class="small text-muted"><?= h($r['planner_time'] ?: '') ?></div>
                                </td>
                                <td class="fw-semibold"><?= h($r['title']) ?></td>
                                <td><span class="badge bg-light text-dark border"><?= h($r['type']) ?></span></td>
                                <td><span class="badge <?= $badge ?>"><?= h(ucfirst($status)) ?></span></td>
                                <td class="text-muted small"><?= h($r['notes']) ?></td>
                                <td class="text-end">
                                    <?php if ($status !== 'completed'): ?>
                                        <form method="post" class="d-inline">
                                            <input type="hidden" name="action" value="done">
                                            <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                                            <button class="btn btn-outline-success btn-sm">Done</button>
                                        </form>
                                    <?php endif; ?>

                                    <form method="post" class="d-inline" onsubmit="return confirm('Delete this planner item?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                                        <button class="btn btn-outline-danger btn-sm">Delete</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="plannerModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <form method="post" class="modal-content border-0 shadow">
            <input type="hidden" name="action" value="create">

            <div class="modal-header">
                <h5 class="modal-title">Add Planner Item</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Title *</label>
                    <input type="text" name="title" class="form-control" required>
                </div>

                <div class="row g-3">
                    <div class="col-md-7">
                        <label class="form-label">Date</label>
                        <input type="date" name="planner_date" class="form-control">
                    </div>
                    <div class="col-md-5">
                        <label class="form-label">Time</label>
                        <input type="time" name="planner_time" class="form-control">
                    </div>
                </div>

                <div class="mt-3">
                    <label class="form-label">Type</label>
                    <select name="type" class="form-select">
                        <option value="task">Task</option>
                        <option value="exam">Exam</option>
                        <option value="release">Release</option>
                        <option value="meeting">Meeting</option>
                        <option value="reminder">Reminder</option>
                    </select>
                </div>

                <div class="mt-3">
                    <label class="form-label">Notes</label>
                    <textarea name="notes" rows="4" class="form-control"></textarea>
                </div>
            </div>

            <div class="modal-footer">
                <button class="btn btn-primary">
                    <i class="bi bi-check-circle me-1"></i> Save
                </button>
            </div>
        </form>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/admin_layout_bottom.php'; ?>