<?php
// api/checklist.php — Daily Checklist API
require_once '../lib/db.php';
require_once '../lib/auth.php';

Auth::startSession();
header('Content-Type: application/json');

$db     = Database::connect();
$role   = $_SESSION['user_role']  ?? '';
$userId = $_SESSION['user_id']    ?? 0;
$input  = json_decode(file_get_contents('php://input'), true) ?? [];
$action = $input['action'] ?? ($_GET['action'] ?? '');

// ── helper ──────────────────────────────────────────────────
function ok($data = [])  { echo json_encode(['success' => true]  + $data); exit; }
function err($msg)       { echo json_encode(['success' => false, 'message' => $msg]); exit; }

// ====================================================================
// ADMIN ACTIONS
// ====================================================================
if ($role === 'admin') {

    // ── List all categories ──────────────────────────────────
    if ($action === 'list_categories') {
        $rows = $db->query("SELECT * FROM checklist_categories ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
        ok(['categories' => $rows]);
    }

    // ── Save category (insert or update) ────────────────────
    if ($action === 'save_category') {
        $name = trim($input['name'] ?? '');
        $desc = trim($input['description'] ?? '');
        $id   = intval($input['id'] ?? 0);
        if (!$name) err('Nama kategori wajib diisi.');

        if ($id) {
            $s = $db->prepare("UPDATE checklist_categories SET name=?, description=? WHERE id=?");
            $s->execute([$name, $desc, $id]);
        } else {
            $s = $db->prepare("INSERT INTO checklist_categories (name, description) VALUES (?,?)");
            $s->execute([$name, $desc]);
            $id = $db->lastInsertId();
        }
        ok(['id' => $id]);
    }

    // ── Delete category ──────────────────────────────────────
    if ($action === 'delete_category') {
        $id = intval($input['id'] ?? 0);
        if (!$id) err('ID tidak valid.');
        $db->prepare("DELETE FROM checklist_categories WHERE id=?")->execute([$id]);
        ok();
    }

    // ── List items for a category ────────────────────────────
    if ($action === 'list_items') {
        $catId = intval($input['category_id'] ?? 0);
        if (!$catId) err('category_id wajib.');
        $rows = $db->prepare("SELECT * FROM checklist_items WHERE category_id=? ORDER BY phase, sort_order, id");
        $rows->execute([$catId]);
        ok(['items' => $rows->fetchAll(PDO::FETCH_ASSOC)]);
    }

    // ── Save item ────────────────────────────────────────────
    if ($action === 'save_item') {
        $catId = intval($input['category_id'] ?? 0);
        $phase = $input['phase'] ?? 'all';
        $task  = trim($input['task'] ?? '');
        $order = intval($input['sort_order'] ?? 0);
        $id    = intval($input['id'] ?? 0);
        if (!$task || !$catId) err('task dan category_id wajib.');
        if (!in_array($phase, ['opening','closing','all'])) $phase = 'all';

        if ($id) {
            $s = $db->prepare("UPDATE checklist_items SET category_id=?, phase=?, sort_order=?, task=? WHERE id=?");
            $s->execute([$catId, $phase, $order, $task, $id]);
        } else {
            $s = $db->prepare("INSERT INTO checklist_items (category_id, phase, sort_order, task) VALUES (?,?,?,?)");
            $s->execute([$catId, $phase, $order, $task]);
            $id = $db->lastInsertId();
        }
        ok(['id' => $id]);
    }

    // ── Delete item ──────────────────────────────────────────
    if ($action === 'delete_item') {
        $id = intval($input['id'] ?? 0);
        if (!$id) err('ID tidak valid.');
        $db->prepare("DELETE FROM checklist_items WHERE id=?")->execute([$id]);
        ok();
    }

    // ── Assign category to user ──────────────────────────────
    if ($action === 'assign_category') {
        $empId = intval($input['employee_id'] ?? 0);
        $catId = intval($input['category_id'] ?? 0) ?: null;
        if (!$empId) err('employee_id wajib.');
        $db->prepare("UPDATE users SET category_id=? WHERE id=?")->execute([$catId, $empId]);
        ok();
    }

    // ── Get today's checklist progress (all categories) ─────
    if ($action === 'admin_today_progress') {
        $today = date('Y-m-d');
        $sql = "
            SELECT ci.id, ci.phase, ci.task, ci.sort_order, cc.name AS category_name, cc.id AS category_id,
                   cl.user_id AS checked_by, u.full_name AS checker_name, cl.checked_at
            FROM checklist_items ci
            JOIN checklist_categories cc ON ci.category_id = cc.id
            LEFT JOIN checklist_logs cl ON cl.item_id = ci.id AND cl.log_date = ?
            LEFT JOIN users u ON u.id = cl.user_id
            ORDER BY cc.name, ci.phase, ci.sort_order
        ";
        $s = $db->prepare($sql);
        $s->execute([$today]);
        ok(['items' => $s->fetchAll(PDO::FETCH_ASSOC)]);
    }
}

// ====================================================================
// EMPLOYEE ACTIONS
// ====================================================================
if ($role === 'employee') {

    // ── Get today's checklist for this employee's category ───
    if ($action === 'my_checklist') {
        $today = date('Y-m-d');

        // Get user's category_id
        $su = $db->prepare("SELECT category_id FROM users WHERE id=?");
        $su->execute([$userId]);
        $catId = $su->fetchColumn();

        if (!$catId) ok(['items' => [], 'category' => null]);

        $sc = $db->prepare("SELECT * FROM checklist_categories WHERE id=?");
        $sc->execute([$catId]);
        $category = $sc->fetch(PDO::FETCH_ASSOC);

        $sql = "
            SELECT ci.id, ci.phase, ci.task, ci.sort_order,
                   cl.user_id AS checked_by, u.full_name AS checker_name, cl.checked_at
            FROM checklist_items ci
            LEFT JOIN checklist_logs cl ON cl.item_id = ci.id AND cl.log_date = ?
            LEFT JOIN users u ON u.id = cl.user_id
            WHERE ci.category_id = ?
            ORDER BY ci.phase, ci.sort_order, ci.id
        ";
        $s = $db->prepare($sql);
        $s->execute([$today, $catId]);
        ok(['items' => $s->fetchAll(PDO::FETCH_ASSOC), 'category' => $category]);
    }

    // ── Toggle (check) an item ───────────────────────────────
    if ($action === 'toggle_item') {
        $itemId = intval($input['item_id'] ?? 0);
        $today  = date('Y-m-d');
        if (!$itemId) err('item_id wajib.');

        // Verify item belongs to user's category
        $su = $db->prepare("SELECT category_id FROM users WHERE id=?");
        $su->execute([$userId]);
        $catId = $su->fetchColumn();
        if (!$catId) err('Anda tidak memiliki kategori checklist.');

        $sv = $db->prepare("SELECT id FROM checklist_items WHERE id=? AND category_id=?");
        $sv->execute([$itemId, $catId]);
        if (!$sv->fetch()) err('Item tidak ditemukan dalam kategori Anda.');

        // Check if already checked today
        $sc = $db->prepare("SELECT id, user_id FROM checklist_logs WHERE item_id=? AND log_date=?");
        $sc->execute([$itemId, $today]);
        $existing = $sc->fetch(PDO::FETCH_ASSOC);

        if ($existing) {
            // Only allow unchecking if it's the same user
            if (intval($existing['user_id']) !== $userId) {
                err('Item ini sudah dicentang oleh orang lain hari ini.');
            }
            // Uncheck
            $db->prepare("DELETE FROM checklist_logs WHERE item_id=? AND log_date=? AND user_id=?")
               ->execute([$itemId, $today, $userId]);
            ok(['checked' => false]);
        } else {
            // Check
            $db->prepare("INSERT INTO checklist_logs (item_id, user_id, log_date) VALUES (?,?,?)")
               ->execute([$itemId, $userId, $today]);
            ok(['checked' => true, 'checker_name' => $_SESSION['user_name'] ?? 'Anda']);
        }
    }
}

err('Aksi tidak dikenal atau tidak diizinkan.');
