<?php
class DependentApiController extends Controller
{
    public function datatable(Request $request): void
    {
        $memberId = (int) $request->routeParam('id');
        $db = Database::getInstance();

        $rows = $db->fetchAll(
            "SELECT d.*, rt.name_en AS rel_type_en, rt.name_ar AS rel_type_ar
             FROM member_dependents d
             LEFT JOIN dependent_relationship_types rt ON d.relationship_type_id = rt.id
             WHERE d.primary_member_id = ? AND d.is_deleted = 0
             ORDER BY d.add_date", [$memberId]
        );

        $data = [];
        foreach ($rows as $row) {
            $age = $row['date_of_birth'] ? (int) ((time() - strtotime($row['date_of_birth'])) / 31557600) : '—';
            $actions = '<div class="btn-group btn-group-sm">';
            if (Gate::can('dependents.manage')) {
                $actions .= '<button class="btn btn-outline-warning btn-edit-dep" data-id="' . $row['id'] . '" title="Edit"><i class="fas fa-edit"></i></button>';
                $actions .= '<button class="btn btn-outline-danger btn-delete-dep" data-id="' . $row['id'] . '" title="Remove"><i class="fas fa-trash"></i></button>';
            }
            $actions .= '</div>';

            $data[] = [
                'id'           => $row['id'],
                'name'         => e($row['full_name_en']),
                'name_ar'      => e($row['full_name_ar'] ?? ''),
                'relationship' => e(current_lang() === 'ar' ? $row['rel_type_ar'] : $row['rel_type_en']),
                'gender'       => ucfirst($row['gender']),
                'dob'          => format_date($row['date_of_birth']),
                'age'          => $age,
                'national_id'  => e($row['national_id'] ?? '—'),
                'status'       => status_badge($row['status']),
                'actions'      => $actions,
            ];
        }

        $this->json([
            'draw'            => (int) $request->get('draw', 1),
            'recordsTotal'    => count($data),
            'recordsFiltered' => count($data),
            'data'            => $data,
        ]);
    }

    public function get(Request $request): void
    {
        $depId = (int) $request->routeParam('depId');
        $db = Database::getInstance();
        $dep = $db->fetchOne("SELECT * FROM member_dependents WHERE id = ? AND is_deleted = 0", [$depId]);
        if (!$dep) {
            $this->json(['success' => false, 'message' => 'Dependent not found'], 404);
            return;
        }
        $this->json(['success' => true, 'data' => $dep]);
    }

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

        $memberId = (int) $request->routeParam('id');
        $db = Database::getInstance();

        $member = $db->fetchOne("SELECT id, family_id, membership_type_id FROM members WHERE id = ? AND is_deleted = 0", [$memberId]);
        if (!$member) {
            $this->json(['success' => false, 'message' => 'Member not found'], 404);
            return;
        }

        $memType = $db->fetchOne("SELECT max_dependents, is_family_membership FROM membership_types WHERE id = ?", [$member['membership_type_id']]);
        if (!$memType || !$memType['is_family_membership']) {
            $this->json(['success' => false, 'message' => 'This membership type does not allow dependents'], 422);
            return;
        }

        $currentCount = (int) $db->fetchColumn("SELECT COUNT(*) FROM member_dependents WHERE primary_member_id = ? AND is_deleted = 0", [$memberId]);
        if ($memType['max_dependents'] !== null && $currentCount >= $memType['max_dependents']) {
            $this->json(['success' => false, 'message' => 'Maximum dependents limit reached (' . $memType['max_dependents'] . ')'], 422);
            return;
        }

        $validator = new Validator($request->all(), [
            'relationship_type_id' => 'required|integer|exists:dependent_relationship_types,id',
            'first_name_en'        => 'required|string|max:100',
            'last_name_en'         => 'required|string|max:100',
            'gender'               => 'required|in:male,female',
            'date_of_birth'        => 'nullable|date',
            'national_id'          => 'nullable|string|max:20',
            'phone'                => 'nullable|string|max:20',
        ]);

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

        $data = $validator->validated();

        // Validate relationship type constraints
        $relType = $db->fetchOne("SELECT * FROM dependent_relationship_types WHERE id = ?", [$data['relationship_type_id']]);
        if ($relType) {
            if ($relType['gender_restriction'] !== 'both' && $data['gender'] !== $relType['gender_restriction']) {
                $this->json(['success' => false, 'errors' => ['gender' => ['Gender does not match relationship type requirement']]], 422);
                return;
            }
            if ($relType['max_count_per_member']) {
                $relCount = (int) $db->fetchColumn("SELECT COUNT(*) FROM member_dependents WHERE primary_member_id = ? AND relationship_type_id = ? AND is_deleted = 0", [$memberId, $data['relationship_type_id']]);
                if ($relCount >= $relType['max_count_per_member']) {
                    $this->json(['success' => false, 'message' => 'Maximum count for this relationship type reached'], 422);
                    return;
                }
            }
        }

        $familyId = $member['family_id'];
        if (!$familyId) {
            $familyCode = 'FAM-' . str_pad($memberId, 6, '0', STR_PAD_LEFT);
            $familyId = $db->insert('member_families', [
                'family_code'       => $familyCode,
                'primary_member_id' => $memberId,
                'created_by'        => Auth::id(),
            ]);
            $db->update('members', ['family_id' => $familyId], 'id = ?', [$memberId]);
        }

        $fullNameEn = trim(($data['first_name_en'] ?? '') . ' ' . ($request->post('second_name_en', '')) . ' ' . ($request->post('third_name_en', '')) . ' ' . ($data['last_name_en'] ?? ''));
        $fullNameEn = preg_replace('/\s+/', ' ', $fullNameEn);

        $depId = $db->insert('member_dependents', [
            'family_id'            => $familyId,
            'primary_member_id'    => $memberId,
            'relationship_type_id' => $data['relationship_type_id'],
            'first_name_en'        => $data['first_name_en'],
            'second_name_en'       => $request->post('second_name_en'),
            'third_name_en'        => $request->post('third_name_en'),
            'last_name_en'         => $data['last_name_en'],
            'full_name_en'         => $fullNameEn,
            'first_name_ar'        => $request->post('first_name_ar'),
            'last_name_ar'         => $request->post('last_name_ar'),
            'national_id'          => $data['national_id'] ?? null,
            'date_of_birth'        => $data['date_of_birth'] ?? null,
            'gender'               => $data['gender'],
            'phone'                => $data['phone'] ?? null,
            'status'               => 'active',
            'add_date'             => date('Y-m-d'),
            'created_by'           => Auth::id(),
        ]);

        AuditLog::log('create', 'members', 'member_dependents', $depId, "Added dependent to member {$memberId}");

        $this->json(['success' => true, 'message' => 'Dependent added successfully', 'id' => $depId]);
    }

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

        $depId = (int) $request->routeParam('depId');
        $db = Database::getInstance();

        $validator = new Validator($request->all(), [
            'relationship_type_id' => 'required|integer|exists:dependent_relationship_types,id',
            'first_name_en'        => 'required|string|max:100',
            'last_name_en'         => 'required|string|max:100',
            'gender'               => 'required|in:male,female',
            'date_of_birth'        => 'nullable|date',
            'national_id'          => 'nullable|string|max:20',
            'phone'                => 'nullable|string|max:20',
        ]);

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

        $data = $validator->validated();
        $fullNameEn = trim(($data['first_name_en'] ?? '') . ' ' . ($request->post('second_name_en', '')) . ' ' . ($request->post('third_name_en', '')) . ' ' . ($data['last_name_en'] ?? ''));
        $fullNameEn = preg_replace('/\s+/', ' ', $fullNameEn);

        $db->update('member_dependents', [
            'relationship_type_id' => $data['relationship_type_id'],
            'first_name_en'        => $data['first_name_en'],
            'second_name_en'       => $request->post('second_name_en'),
            'third_name_en'        => $request->post('third_name_en'),
            'last_name_en'         => $data['last_name_en'],
            'full_name_en'         => $fullNameEn,
            'first_name_ar'        => $request->post('first_name_ar'),
            'last_name_ar'         => $request->post('last_name_ar'),
            'national_id'          => $data['national_id'] ?? null,
            'date_of_birth'        => $data['date_of_birth'] ?? null,
            'gender'               => $data['gender'],
            'phone'                => $data['phone'] ?? null,
        ], 'id = ?', [$depId]);

        AuditLog::log('update', 'members', 'member_dependents', $depId, "Updated dependent");

        $this->json(['success' => true, 'message' => 'Dependent updated']);
    }

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

        $depId = (int) $request->routeParam('depId');
        $db = Database::getInstance();

        $db->update('member_dependents', [
            'is_deleted'    => 1,
            'status'        => 'removed',
            'status_reason' => 'Removed by staff',
            'removal_date'  => date('Y-m-d'),
            'status_changed_at' => date('Y-m-d H:i:s'),
        ], 'id = ?', [$depId]);

        AuditLog::log('delete', 'members', 'member_dependents', $depId, "Removed dependent");

        $this->json(['success' => true, 'message' => 'Dependent removed']);
    }
}