<?php
class BoardMemberController extends Controller
{
    public function index(Request $request): void
    {
        $terms = $this->db()->fetchAll("SELECT id, term_name_en, term_name_ar, status FROM board_terms ORDER BY start_date DESC");
        $positions = $this->db()->fetchAll("SELECT id, title_en, title_ar FROM board_positions WHERE is_active = 1 ORDER BY sort_order");

        $this->view('members/index', [
            'title' => lang('board.board_members'),
            'breadcrumbs' => [
                ['label' => lang('board.module'), 'url' => '/board/terms'],
                ['label' => lang('board.board_members')]
            ],
            'terms' => $terms,
            'positions' => $positions,
        ]);
    }

    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'] ?? '';
        $termFilter = $request->get('term_id', '');
        $statusFilter = $request->get('status', '');

        $where = '1=1';
        $params = [];
        if ($search) {
            $where .= " AND (bm.full_name_en LIKE ? OR bm.full_name_ar LIKE ?)";
            $params[] = "%{$search}%";
            $params[] = "%{$search}%";
        }
        if ($termFilter) {
            $where .= " AND bm.term_id = ?";
            $params[] = $termFilter;
        }
        if ($statusFilter) {
            $where .= " AND bm.status = ?";
            $params[] = $statusFilter;
        }

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

        $rows = $db->fetchAll(
            "SELECT bm.*, bp.title_en as position_title, bp.title_ar as position_title_ar,
                    bt.term_name_en, bt.term_name_ar
             FROM board_members bm
             LEFT JOIN board_positions bp ON bm.position_id = bp.id
             LEFT JOIN board_terms bt ON bm.term_id = bt.id
             WHERE {$where}
             ORDER BY bt.start_date DESC, bp.sort_order ASC
             LIMIT {$length} OFFSET {$start}",
            $params
        );

        $data = [];
        foreach ($rows as $row) {
            $actions = '';
            if (auth_can('board.manage')) {
                $actions .= '<a href="/board/members/' . $row['id'] . '/edit" class="btn btn-sm btn-outline-warning me-1"><i class="fas fa-edit"></i></a>';
                if ($row['status'] === 'active') {
                    $actions .= '<button class="btn btn-sm btn-outline-secondary me-1 btn-resign" data-id="' . $row['id'] . '"><i class="fas fa-user-slash"></i></button>';
                }
                $actions .= '<form method="POST" action="/board/members/' . $row['id'] . '/delete" class="d-inline" data-confirm="true"><input type="hidden" name="_token" value="' . csrf_token() . '"><button class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button></form>';
            }

            $data[] = [
                'id' => $row['id'],
                'name' => e(current_lang() === 'ar' ? ($row['full_name_ar'] ?: $row['full_name_en']) : $row['full_name_en']),
                'position' => e(current_lang() === 'ar' ? ($row['position_title_ar'] ?: $row['position_title']) : $row['position_title']),
                'term' => e(current_lang() === 'ar' ? ($row['term_name_ar'] ?: $row['term_name_en']) : $row['term_name_en']),
                'start_date' => format_date($row['start_date']),
                'status' => status_badge($row['status']),
                '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");
        $positions = $this->db()->fetchAll("SELECT id, title_en, title_ar FROM board_positions WHERE is_active = 1 ORDER BY sort_order");

        $this->view('members/form', [
            'title' => lang('board.add_member'),
            'breadcrumbs' => [
                ['label' => lang('board.module'), 'url' => '/board/terms'],
                ['label' => lang('board.board_members'), 'url' => '/board/members'],
                ['label' => lang('common.create')]
            ],
            'boardMember' => null,
            'terms' => $terms,
            'positions' => $positions,
            'formAction' => '/board/members',
        ]);
    }

    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(), [
            'term_id'       => 'required|integer|exists:board_terms,id',
            'position_id'   => 'required|integer|exists:board_positions,id',
            'full_name_en'  => 'required|string|max:300',
            'full_name_ar'  => 'nullable|string|max:300',
            'member_id'     => 'nullable|integer',
            'user_id'       => 'nullable|integer',
            'start_date'    => 'required|date',
            'end_date'      => 'nullable|date',
            'notes'         => 'nullable|string|max:5000',
        ]);

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

        $data = $validator->validated();
        $data['status'] = 'active';
        $id = $this->db()->insert('board_members', $data);

        $this->audit('create', 'board_members', $id, 'Added board member: ' . $data['full_name_en']);
        $this->json(['success' => true, 'message' => lang('board.member_added'), 'redirect' => '/board/members']);
    }

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

        $terms = $this->db()->fetchAll("SELECT id, term_name_en, term_name_ar FROM board_terms ORDER BY start_date DESC");
        $positions = $this->db()->fetchAll("SELECT id, title_en, title_ar FROM board_positions WHERE is_active = 1 ORDER BY sort_order");

        $this->view('members/form', [
            'title' => lang('board.edit_member'),
            'breadcrumbs' => [
                ['label' => lang('board.module'), 'url' => '/board/terms'],
                ['label' => lang('board.board_members'), 'url' => '/board/members'],
                ['label' => lang('common.edit')]
            ],
            'boardMember' => $boardMember,
            'terms' => $terms,
            'positions' => $positions,
            'formAction' => '/board/members/' . $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_members WHERE id = ?", [$id]);
        if (!$old) { $this->json(['success' => false, 'message' => 'Not found'], 404); return; }

        $validator = new Validator($request->all(), [
            'term_id'       => 'required|integer|exists:board_terms,id',
            'position_id'   => 'required|integer|exists:board_positions,id',
            'full_name_en'  => 'required|string|max:300',
            'full_name_ar'  => 'nullable|string|max:300',
            'member_id'     => 'nullable|integer',
            'user_id'       => 'nullable|integer',
            'start_date'    => 'required|date',
            'end_date'      => 'nullable|date',
            'status'        => 'required|in:active,resigned,removed,term_ended',
            'notes'         => 'nullable|string|max:5000',
        ]);

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

        $data = $validator->validated();
        $this->db()->update('board_members', $data, 'id = ?', [$id]);

        $this->audit('update', 'board_members', $id, 'Updated board member: ' . $data['full_name_en'], $old, $data);
        $this->json(['success' => true, 'message' => lang('board.member_updated'), 'redirect' => '/board/members']);
    }

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

        $bm = $this->db()->fetchOne("SELECT * FROM board_members WHERE id = ? AND status = 'active'", [$id]);
        if (!$bm) { $this->json(['success' => false, 'message' => 'Not found or not active'], 404); return; }

        $reason = $request->post('resignation_reason', '');
        $this->db()->update('board_members', [
            'status' => 'resigned',
            'resignation_date' => date('Y-m-d'),
            'resignation_reason' => $reason,
            'end_date' => date('Y-m-d'),
        ], 'id = ?', [$id]);

        $this->audit('update', 'board_members', $id, 'Board member resigned: ' . $bm['full_name_en']);
        $this->json(['success' => true, 'message' => lang('board.member_resigned')]);
    }

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

        $this->db()->delete('board_committee_members', 'board_member_id = ?', [$id]);
        $this->db()->delete('board_members', 'id = ?', [$id]);
        $this->audit('delete', 'board_members', $id, 'Deleted board member');
        $this->json(['success' => true, 'message' => lang('board.member_deleted'), 'redirect' => '/board/members']);
    }
}