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

    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'] ?? '';
        $orderCol = (int) ($request->get('order')[0]['column'] ?? 0);
        $orderDir = ($request->get('order')[0]['dir'] ?? 'desc') === 'asc' ? 'ASC' : 'DESC';

        $columns = ['id', 'term_name_en', 'start_date', 'end_date', 'status', 'created_at'];
        $orderBy = $columns[$orderCol] ?? 'id';

        $where = '1=1';
        $params = [];
        if ($search) {
            $where .= " AND (term_name_en LIKE ? OR term_name_ar LIKE ?)";
            $params[] = "%{$search}%";
            $params[] = "%{$search}%";
        }

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

        $rows = $db->fetchAll(
            "SELECT * FROM board_terms WHERE {$where} ORDER BY {$orderBy} {$orderDir} LIMIT {$length} OFFSET {$start}",
            $params
        );

        $data = [];
        foreach ($rows as $row) {
            $memberCount = (int) $db->fetchColumn("SELECT COUNT(*) FROM board_members WHERE term_id = ? AND status = 'active'", [$row['id']]);
            $actions = '';
            if (auth_can('board.view')) {
                $actions .= '<a href="/board/terms/' . $row['id'] . '" class="btn btn-sm btn-outline-primary me-1" title="View"><i class="fas fa-eye"></i></a>';
            }
            if (auth_can('board.manage')) {
                $actions .= '<a href="/board/terms/' . $row['id'] . '/edit" class="btn btn-sm btn-outline-warning me-1" title="Edit"><i class="fas fa-edit"></i></a>';
                $actions .= '<form method="POST" action="/board/terms/' . $row['id'] . '/delete" class="d-inline" data-confirm="true"><input type="hidden" name="_token" value="' . csrf_token() . '"><button type="submit" class="btn btn-sm btn-outline-danger" title="Delete"><i class="fas fa-trash"></i></button></form>';
            }

            $data[] = [
                'id' => $row['id'],
                'term_name' => e(current_lang() === 'ar' ? ($row['term_name_ar'] ?: $row['term_name_en']) : $row['term_name_en']),
                'start_date' => format_date($row['start_date']),
                'end_date' => format_date($row['end_date']),
                'status' => status_badge($row['status']),
                'members' => $memberCount,
                'actions' => $actions,
            ];
        }

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

    public function create(Request $request): void
    {
        $this->view('terms/form', [
            'title' => lang('board.create_term'),
            'breadcrumbs' => [
                ['label' => lang('board.module'), 'url' => '/board/terms'],
                ['label' => lang('board.terms'), 'url' => '/board/terms'],
                ['label' => lang('common.create')]
            ],
            'term' => null,
            'formAction' => '/board/terms',
        ]);
    }

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

        $validator = new Validator($request->all(), [
            'term_name_en' => 'required|string|max:200',
            'term_name_ar' => 'required|string|max:200',
            'start_date'   => 'required|date',
            'end_date'     => 'required|date',
            'status'       => 'required|in:upcoming,active,ended',
            'election_date'=> 'nullable|date',
            'notes'        => 'nullable|string|max:5000',
        ]);

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

        $data = $validator->validated();
        $id = $this->db()->insert('board_terms', $data);

        $this->audit('create', 'board_terms', $id, 'Created board term: ' . $data['term_name_en']);
        $this->json(['success' => true, 'message' => lang('board.term_created'), 'redirect' => '/board/terms']);
    }

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

        $members = $this->db()->fetchAll(
            "SELECT bm.*, bp.title_en as position_title, bp.title_ar as position_title_ar
             FROM board_members bm
             LEFT JOIN board_positions bp ON bm.position_id = bp.id
             WHERE bm.term_id = ?
             ORDER BY bp.sort_order ASC",
            [$id]
        );

        $meetings = $this->db()->fetchAll("SELECT * FROM board_meetings WHERE term_id = ? ORDER BY meeting_date DESC LIMIT 10", [$id]);
        $resolutions = $this->db()->fetchAll("SELECT * FROM board_resolutions WHERE term_id = ? ORDER BY resolution_date DESC LIMIT 10", [$id]);

        $this->view('terms/show', [
            'title' => e($term['term_name_en']),
            'breadcrumbs' => [
                ['label' => lang('board.module'), 'url' => '/board/terms'],
                ['label' => lang('board.terms'), 'url' => '/board/terms'],
                ['label' => e($term['term_name_en'])]
            ],
            'term' => $term,
            'members' => $members,
            'meetings' => $meetings,
            'resolutions' => $resolutions,
        ]);
    }

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

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

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

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

        $validator = new Validator($request->all(), [
            'term_name_en' => 'required|string|max:200',
            'term_name_ar' => 'required|string|max:200',
            'start_date'   => 'required|date',
            'end_date'     => 'required|date',
            'status'       => 'required|in:upcoming,active,ended',
            'election_date'=> 'nullable|date',
            'notes'        => 'nullable|string|max:5000',
        ]);

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

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

        $this->audit('update', 'board_terms', $id, 'Updated board term: ' . $data['term_name_en'], $term, $data);
        $this->json(['success' => true, 'message' => lang('board.term_updated'), 'redirect' => '/board/terms']);
    }

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

        $memberCount = (int) $this->db()->fetchColumn("SELECT COUNT(*) FROM board_members WHERE term_id = ?", [$id]);
        if ($memberCount > 0) {
            $this->json(['success' => false, 'message' => 'Cannot delete term with board members assigned'], 400);
            return;
        }

        $this->db()->delete('board_terms', 'id = ?', [$id]);
        $this->audit('delete', 'board_terms', $id, 'Deleted board term');
        $this->json(['success' => true, 'message' => lang('board.term_deleted'), 'redirect' => '/board/terms']);
    }
}