<?php
class CommitteeController extends Controller
{
    public function index(Request $request): void
    {
        $this->view('committees/index', [
            'title' => lang('board.committees'),
            'breadcrumbs' => [
                ['label' => lang('board.module'), 'url' => '/board/terms'],
                ['label' => lang('board.committees')]
            ],
        ]);
    }

    public function datatable(Request $request): void
    {
        $db = $this->db();
        $draw = (int) $request->get('draw', 1);
        $start = (int) $request->get('start', 0);
        $length = (int) $request->get('length', 25);
        $search = $request->get('search')['value'] ?? '';

        $where = '1=1';
        $params = [];
        if ($search) {
            $where .= " AND (c.name_en LIKE ? OR c.name_ar LIKE ? OR c.committee_code LIKE ?)";
            $params = array_merge($params, ["%{$search}%", "%{$search}%", "%{$search}%"]);
        }

        $total = (int) $db->fetchColumn("SELECT COUNT(*) FROM board_committees");
        $filtered = (int) $db->fetchColumn("SELECT COUNT(*) FROM board_committees c WHERE {$where}", $params);

        $rows = $db->fetchAll(
            "SELECT c.*, bt.term_name_en, bt.term_name_ar,
                    (SELECT COUNT(*) FROM board_committee_members bcm WHERE bcm.committee_id = c.id AND bcm.is_active = 1) as member_count
             FROM board_committees c
             LEFT JOIN board_terms bt ON c.term_id = bt.id
             WHERE {$where}
             ORDER BY c.created_at DESC
             LIMIT {$length} OFFSET {$start}",
            $params
        );

        $data = [];
        foreach ($rows as $row) {
            $actions = '';
            if (auth_can('board.manage')) {
                $actions .= '<a href="/board/committees/' . $row['id'] . '/edit" class="btn btn-sm btn-outline-warning me-1"><i class="fas fa-edit"></i></a>';
            }
            $data[] = [
                'id' => $row['id'],
                'code' => e($row['committee_code']),
                'name' => e(current_lang() === 'ar' ? ($row['name_ar'] ?: $row['name_en']) : $row['name_en']),
                'term' => e(current_lang() === 'ar' ? ($row['term_name_ar'] ?: $row['term_name_en']) : $row['term_name_en']),
                'members' => $row['member_count'],
                'status' => $row['is_active'] ? status_badge('active') : status_badge('expired'),
                'actions' => $actions,
            ];
        }

        $this->json(['draw' => $draw, 'recordsTotal' => $total, 'recordsFiltered' => $filtered, 'data' => $data]);
    }

    public function create(Request $request): void
    {
        $terms = $this->db()->fetchAll("SELECT id, term_name_en, term_name_ar FROM board_terms WHERE status IN ('upcoming','active') ORDER BY start_date DESC");
        $boardMembers = $this->db()->fetchAll("SELECT id, full_name_en, full_name_ar FROM board_members WHERE status = 'active' ORDER BY full_name_en");

        $this->view('committees/form', [
            'title' => lang('board.create_committee'),
            'breadcrumbs' => [
                ['label' => lang('board.module'), 'url' => '/board/terms'],
                ['label' => lang('board.committees'), 'url' => '/board/committees'],
                ['label' => lang('common.create')]
            ],
            'committee' => null,
            'terms' => $terms,
            'boardMembers' => $boardMembers,
            'committeeMembers' => [],
            'formAction' => '/board/committees',
        ]);
    }

    public function store(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) {
            $this->json(['success' => false, 'message' => 'Invalid token'], 403);
            return;
        }

        $validator = new Validator($request->all(), [
            'committee_code' => 'required|string|max:20|unique:board_committees,committee_code',
            'name_en'        => 'required|string|max:200',
            'name_ar'        => 'required|string|max:200',
            'term_id'        => 'required|integer|exists:board_terms,id',
            'chairperson_board_member_id' => 'nullable|integer',
            'description_en' => 'nullable|string|max:5000',
            'description_ar' => 'nullable|string|max:5000',
        ]);

        if ($validator->fails()) {
            $this->json(['success' => false, 'errors' => $validator->errors()], 422);
            return;
        }

        $data = $validator->validated();
        $data['is_active'] = 1;
        $id = $this->db()->insert('board_committees', $data);

        $this->audit('create', 'board_committees', $id, 'Created committee: ' . $data['name_en']);
        $this->json(['success' => true, 'message' => lang('board.committee_created'), 'redirect' => '/board/committees']);
    }

    public function edit(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $committee = $this->db()->fetchOne("SELECT * FROM board_committees WHERE id = ?", [$id]);
        if (!$committee) { $this->abort(404); return; }

        $terms = $this->db()->fetchAll("SELECT id, term_name_en, term_name_ar FROM board_terms ORDER BY start_date DESC");
        $boardMembers = $this->db()->fetchAll("SELECT id, full_name_en, full_name_ar FROM board_members WHERE status = 'active' ORDER BY full_name_en");
        $committeeMembers = $this->db()->fetchAll(
            "SELECT bcm.*, bm.full_name_en, bm.full_name_ar
             FROM board_committee_members bcm
             JOIN board_members bm ON bcm.board_member_id = bm.id
             WHERE bcm.committee_id = ? AND bcm.is_active = 1
             ORDER BY bm.full_name_en",
            [$id]
        );

        $this->view('committees/form', [
            'title' => lang('board.edit_committee'),
            'breadcrumbs' => [
                ['label' => lang('board.module'), 'url' => '/board/terms'],
                ['label' => lang('board.committees'), 'url' => '/board/committees'],
                ['label' => lang('common.edit')]
            ],
            'committee' => $committee,
            'terms' => $terms,
            'boardMembers' => $boardMembers,
            'committeeMembers' => $committeeMembers,
            'formAction' => '/board/committees/' . $id,
        ]);
    }

    public function update(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) {
            $this->json(['success' => false, 'message' => 'Invalid token'], 403);
            return;
        }

        $old = $this->db()->fetchOne("SELECT * FROM board_committees WHERE id = ?", [$id]);
        if (!$old) { $this->json(['success' => false, 'message' => 'Not found'], 404); return; }

        $validator = new Validator($request->all(), [
            'committee_code' => 'required|string|max:20|unique:board_committees,committee_code,' . $id,
            'name_en'        => 'required|string|max:200',
            'name_ar'        => 'required|string|max:200',
            'term_id'        => 'required|integer|exists:board_terms,id',
            'chairperson_board_member_id' => 'nullable|integer',
            'description_en' => 'nullable|string|max:5000',
            'description_ar' => 'nullable|string|max:5000',
            'is_active'      => 'nullable|boolean',
        ]);

        if ($validator->fails()) {
            $this->json(['success' => false, 'errors' => $validator->errors()], 422);
            return;
        }

        $data = $validator->validated();
        $data['is_active'] = $request->post('is_active') ? 1 : 0;
        $this->db()->update('board_committees', $data, 'id = ?', [$id]);

        $this->audit('update', 'board_committees', $id, 'Updated committee: ' . $data['name_en'], $old, $data);
        $this->json(['success' => true, 'message' => lang('board.committee_updated'), 'redirect' => '/board/committees']);
    }

    public function addMember(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) {
            $this->json(['success' => false, 'message' => 'Invalid token'], 403);
            return;
        }

        $boardMemberId = (int) $request->post('board_member_id');
        $role = $request->post('role_in_committee', '');

        $exists = $this->db()->fetchColumn(
            "SELECT COUNT(*) FROM board_committee_members WHERE committee_id = ? AND board_member_id = ? AND is_active = 1",
            [$id, $boardMemberId]
        );
        if ($exists > 0) {
            $this->json(['success' => false, 'message' => 'Member already in this committee'], 400);
            return;
        }

        $this->db()->insert('board_committee_members', [
            'committee_id' => $id,
            'board_member_id' => $boardMemberId,
            'role_in_committee' => $role,
            'joined_date' => date('Y-m-d'),
            'is_active' => 1,
        ]);

        $this->audit('create', 'board_committee_members', null, "Added member {$boardMemberId} to committee {$id}");
        $this->json(['success' => true, 'message' => lang('board.member_added_to_committee')]);
    }

    public function removeMember(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) {
            $this->json(['success' => false, 'message' => 'Invalid token'], 403);
            return;
        }

        $boardMemberId = (int) $request->post('board_member_id');
        $this->db()->update('board_committee_members', [
            'is_active' => 0,
            'left_date' => date('Y-m-d'),
        ], 'committee_id = ? AND board_member_id = ?', [$id, $boardMemberId]);

        $this->audit('update', 'board_committee_members', null, "Removed member {$boardMemberId} from committee {$id}");
        $this->json(['success' => true, 'message' => lang('board.member_removed_from_committee')]);
    }
}