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

    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 (r.resolution_number LIKE ? OR r.title_en LIKE ? OR r.title_ar LIKE ?)";
            $params = array_merge($params, ["%{$search}%", "%{$search}%", "%{$search}%"]);
        }

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

        $rows = $db->fetchAll(
            "SELECT r.*, bm.meeting_number
             FROM board_resolutions r
             LEFT JOIN board_meetings bm ON r.meeting_id = bm.id
             WHERE {$where} ORDER BY r.resolution_date DESC LIMIT {$length} OFFSET {$start}",
            $params
        );

        $data = [];
        foreach ($rows as $row) {
            $votesSummary = "{$row['votes_for']}F / {$row['votes_against']}A / {$row['votes_abstain']}Ab";
            $actions = '<a href="/board/resolutions/' . $row['id'] . '" class="btn btn-sm btn-outline-primary me-1"><i class="fas fa-eye"></i></a>';
            if (auth_can('board.resolutions')) {
                $actions .= '<a href="/board/resolutions/' . $row['id'] . '/edit" class="btn btn-sm btn-outline-warning me-1"><i class="fas fa-edit"></i></a>';
            }

            $data[] = [
                'id' => $row['id'],
                'number' => e($row['resolution_number']),
                'date' => format_date($row['resolution_date']),
                'title' => e(str_limit(current_lang() === 'ar' ? ($row['title_ar'] ?: $row['title_en']) : $row['title_en'], 60)),
                'meeting' => e($row['meeting_number'] ?? '-'),
                'status' => status_badge($row['status']),
                'votes' => $votesSummary,
                '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 FROM board_terms WHERE status IN ('upcoming','active') ORDER BY start_date DESC");
        $meetings = $this->db()->fetchAll("SELECT id, meeting_number, title_en FROM board_meetings WHERE status IN ('scheduled','in_progress','completed') ORDER BY meeting_date DESC LIMIT 50");

        $this->view('resolutions/form', [
            'title' => lang('board.create_resolution'),
            'breadcrumbs' => [
                ['label' => lang('board.module'), 'url' => '/board/terms'],
                ['label' => lang('board.resolutions'), 'url' => '/board/resolutions'],
                ['label' => lang('common.create')]
            ],
            'resolution' => null,
            'terms' => $terms,
            'meetings' => $meetings,
            'formAction' => '/board/resolutions',
        ]);
    }

    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',
            'meeting_id'             => 'nullable|integer',
            'resolution_date'        => 'required|date',
            'title_en'               => 'required|string|max:500',
            'title_ar'               => 'nullable|string|max:500',
            'resolution_text'        => 'required|string',
            'resolution_text_ar'     => 'nullable|string',
            'category'               => 'nullable|string|max:50',
            'requires_implementation'=> 'nullable|boolean',
            'implementation_deadline'=> 'nullable|date',
        ]);

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

        $data = $validator->validated();
        $resNum = SequenceGenerator::next('resolution_number');
        $data['resolution_number'] = $resNum ?: 'RES-' . str_pad(rand(1, 99999), 5, '0', STR_PAD_LEFT);
        $data['status'] = 'draft';
        $data['requires_implementation'] = $request->post('requires_implementation') ? 1 : 0;
        $data['created_by'] = auth_id();

        $id = $this->db()->insert('board_resolutions', $data);

        $this->audit('create', 'board_resolutions', $id, 'Created resolution: ' . $data['resolution_number']);
        $this->json(['success' => true, 'message' => lang('board.resolution_created'), 'redirect' => '/board/resolutions/' . $id]);
    }

    public function show(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $db = $this->db();

        $resolution = $db->fetchOne(
            "SELECT r.*, bm.meeting_number, bt.term_name_en
             FROM board_resolutions r
             LEFT JOIN board_meetings bm ON r.meeting_id = bm.id
             LEFT JOIN board_terms bt ON r.term_id = bt.id
             WHERE r.id = ?", [$id]
        );
        if (!$resolution) { $this->abort(404); return; }

        $votes = $db->fetchAll(
            "SELECT brv.*, bm.full_name_en, bm.full_name_ar, bp.title_en as position_title
             FROM board_resolution_votes brv
             JOIN board_members bm ON brv.board_member_id = bm.id
             LEFT JOIN board_positions bp ON bm.position_id = bp.id
             WHERE brv.resolution_id = ?
             ORDER BY bp.sort_order", [$id]
        );

        $boardMembers = $db->fetchAll(
            "SELECT bm.id, bm.full_name_en, bm.full_name_ar, bp.title_en as position_title
             FROM board_members bm
             LEFT JOIN board_positions bp ON bm.position_id = bp.id
             WHERE bm.term_id = ? AND bm.status = 'active'
             ORDER BY bp.sort_order", [$resolution['term_id']]
        );

        $supersededBy = null;
        if ($resolution['superseded_by_id']) {
            $supersededBy = $db->fetchOne("SELECT id, resolution_number, title_en FROM board_resolutions WHERE id = ?", [$resolution['superseded_by_id']]);
        }

        $this->view('resolutions/show', [
            'title' => e($resolution['resolution_number']),
            'breadcrumbs' => [
                ['label' => lang('board.module'), 'url' => '/board/terms'],
                ['label' => lang('board.resolutions'), 'url' => '/board/resolutions'],
                ['label' => e($resolution['resolution_number'])]
            ],
            'resolution' => $resolution,
            'votes' => $votes,
            'boardMembers' => $boardMembers,
            'supersededBy' => $supersededBy,
        ]);
    }

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

        $terms = $this->db()->fetchAll("SELECT id, term_name_en FROM board_terms ORDER BY start_date DESC");
        $meetings = $this->db()->fetchAll("SELECT id, meeting_number, title_en FROM board_meetings ORDER BY meeting_date DESC LIMIT 50");

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

        $validator = new Validator($request->all(), [
            'term_id'                => 'required|integer',
            'meeting_id'             => 'nullable|integer',
            'resolution_date'        => 'required|date',
            'title_en'               => 'required|string|max:500',
            'title_ar'               => 'nullable|string|max:500',
            'resolution_text'        => 'required|string',
            'resolution_text_ar'     => 'nullable|string',
            'category'               => 'nullable|string|max:50',
            'status'                 => 'required|in:draft,approved,rejected,implemented,cancelled,superseded',
            'requires_implementation'=> 'nullable|boolean',
            'implementation_deadline'=> 'nullable|date',
            'implementation_notes'   => 'nullable|string',
        ]);

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

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

        $this->audit('update', 'board_resolutions', $id, 'Updated resolution: ' . $old['resolution_number'], $old, $data);
        $this->json(['success' => true, 'message' => lang('board.resolution_updated'), 'redirect' => '/board/resolutions/' . $id]);
    }

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

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

        $votes = $request->post('votes', []);
        $comments = $request->post('vote_comments', []);

        $this->db()->delete('board_resolution_votes', 'resolution_id = ?', [$id]);

        $forCount = 0; $againstCount = 0; $abstainCount = 0;
        foreach ($votes as $bmId => $vote) {
            if (!in_array($vote, ['for', 'against', 'abstain'])) continue;

            $this->db()->insert('board_resolution_votes', [
                'resolution_id' => $id,
                'board_member_id' => (int) $bmId,
                'vote' => $vote,
                'comments' => $comments[$bmId] ?? null,
            ]);

            if ($vote === 'for') $forCount++;
            elseif ($vote === 'against') $againstCount++;
            else $abstainCount++;
        }

        $newStatus = $forCount > $againstCount ? 'approved' : ($againstCount > $forCount ? 'rejected' : $resolution['status']);

        $this->db()->update('board_resolutions', [
            'votes_for' => $forCount,
            'votes_against' => $againstCount,
            'votes_abstain' => $abstainCount,
            'status' => $newStatus,
        ], 'id = ?', [$id]);

        $this->audit('update', 'board_resolutions', $id, "Recorded votes: {$forCount}F/{$againstCount}A/{$abstainCount}Ab → {$newStatus}");
        $this->json(['success' => true, 'message' => lang('board.votes_recorded')]);
    }

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

        $notes = $request->post('implementation_notes', '');
        $this->db()->update('board_resolutions', [
            'status' => 'implemented',
            'implemented_at' => date('Y-m-d H:i:s'),
            'implemented_by' => auth_id(),
            'implementation_notes' => $notes,
        ], 'id = ?', [$id]);

        $this->audit('update', 'board_resolutions', $id, 'Marked resolution as implemented');
        $this->json(['success' => true, 'message' => lang('board.resolution_implemented')]);
    }
}