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

    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 (offer_code LIKE ? OR name_en LIKE ? OR name_ar LIKE ?)";
            $params = ["%{$search}%", "%{$search}%", "%{$search}%"];
        }

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

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

        $data = [];
        foreach ($rows as $row) {
            $actions = '<a href="/offers/' . $row['id'] . '" class="btn btn-sm btn-outline-primary me-1"><i class="fas fa-eye"></i></a>';
            if (auth_can('offers.manage')) {
                $actions .= '<a href="/offers/' . $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['offer_code']),
                'name' => e(current_lang() === 'ar' ? ($row['name_ar'] ?: $row['name_en']) : $row['name_en']),
                'type' => status_badge($row['offer_type']),
                'dates' => format_date($row['start_date']) . ' → ' . format_date($row['end_date']),
                'uses' => $row['current_uses'] . ($row['max_uses'] ? '/' . $row['max_uses'] : ''),
                'status' => status_badge($row['status']),
                'actions' => $actions,
            ];
        }

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

    public function create(Request $request): void
    {
        $membershipTypes = $this->db()->fetchAll("SELECT id, name_en, name_ar FROM membership_types WHERE is_active = 1 ORDER BY sort_order");

        $this->view('offers/form', [
            'title' => lang('board.create_offer'),
            'breadcrumbs' => [
                ['label' => lang('board.transfers_module'), 'url' => '/transfers'],
                ['label' => lang('board.special_offers'), 'url' => '/offers'],
                ['label' => lang('common.create')]
            ],
            'offer' => null,
            'membershipTypes' => $membershipTypes,
            'selectedTypes' => [],
            'formAction' => '/offers',
        ]);
    }

    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(), [
            'offer_code'      => 'required|string|max:30|unique:special_offers,offer_code',
            'name_en'         => 'required|string|max:300',
            'name_ar'         => 'required|string|max:300',
            'description_en'  => 'nullable|string|max:5000',
            'description_ar'  => 'nullable|string|max:5000',
            'offer_type'      => 'required|in:discount,fee_waiver,payment_plan,upgrade,bundle,custom',
            'discount_method' => 'nullable|in:percentage,fixed_amount',
            'discount_value'  => 'nullable|decimal|min:0',
            'start_date'      => 'required|date',
            'end_date'        => 'required|date',
            'max_uses'        => 'nullable|integer|min:0',
            'requires_approval'=> 'nullable|boolean',
            'terms_en'        => 'nullable|string',
            'terms_ar'        => 'nullable|string',
        ]);

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

        $data = $validator->validated();
        $data['requires_approval'] = $request->post('requires_approval') ? 1 : 0;
        $data['status'] = 'draft';
        $data['created_by'] = auth_id();

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

        // Link membership types
        $mtIds = $request->post('membership_type_ids', []);
        if (is_array($mtIds)) {
            foreach ($mtIds as $mtId) {
                $this->db()->insert('special_offer_membership_types', [
                    'offer_id' => $id,
                    'membership_type_id' => (int) $mtId,
                ]);
            }
        }

        $this->audit('create', 'special_offers', $id, 'Created offer: ' . $data['offer_code']);
        $this->json(['success' => true, 'message' => lang('board.offer_created'), 'redirect' => '/offers/' . $id]);
    }

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

        $membershipTypes = $this->db()->fetchAll(
            "SELECT mt.* FROM special_offer_membership_types somt
             JOIN membership_types mt ON somt.membership_type_id = mt.id
             WHERE somt.offer_id = ?", [$id]
        );

        $conditions = $this->db()->fetchAll("SELECT * FROM special_offer_conditions WHERE offer_id = ?", [$id]);
        $applications = $this->db()->fetchAll(
            "SELECT mao.*, m.full_name_en, m.membership_number
             FROM member_applied_offers mao
             JOIN members m ON mao.member_id = m.id
             WHERE mao.offer_id = ?
             ORDER BY mao.applied_date DESC LIMIT 50", [$id]
        );

        $this->view('offers/show', [
            'title' => e($offer['offer_code']),
            'breadcrumbs' => [
                ['label' => lang('board.transfers_module'), 'url' => '/transfers'],
                ['label' => lang('board.special_offers'), 'url' => '/offers'],
                ['label' => e($offer['offer_code'])]
            ],
            'offer' => $offer,
            'membershipTypes' => $membershipTypes,
            'conditions' => $conditions,
            'applications' => $applications,
        ]);
    }

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

        $membershipTypes = $this->db()->fetchAll("SELECT id, name_en, name_ar FROM membership_types WHERE is_active = 1 ORDER BY sort_order");
        $selectedTypes = array_column(
            $this->db()->fetchAll("SELECT membership_type_id FROM special_offer_membership_types WHERE offer_id = ?", [$id]),
            'membership_type_id'
        );

        $this->view('offers/form', [
            'title' => lang('board.edit_offer'),
            'breadcrumbs' => [
                ['label' => lang('board.transfers_module'), 'url' => '/transfers'],
                ['label' => lang('board.special_offers'), 'url' => '/offers'],
                ['label' => lang('common.edit')]
            ],
            'offer' => $offer,
            'membershipTypes' => $membershipTypes,
            'selectedTypes' => $selectedTypes,
            'formAction' => '/offers/' . $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 special_offers WHERE id = ?", [$id]);
        if (!$old) { $this->json(['success' => false, 'message' => 'Not found'], 404); return; }

        $validator = new Validator($request->all(), [
            'offer_code'      => 'required|string|max:30|unique:special_offers,offer_code,' . $id,
            'name_en'         => 'required|string|max:300',
            'name_ar'         => 'required|string|max:300',
            'description_en'  => 'nullable|string|max:5000',
            'description_ar'  => 'nullable|string|max:5000',
            'offer_type'      => 'required|in:discount,fee_waiver,payment_plan,upgrade,bundle,custom',
            'discount_method' => 'nullable|in:percentage,fixed_amount',
            'discount_value'  => 'nullable|decimal|min:0',
            'start_date'      => 'required|date',
            'end_date'        => 'required|date',
            'max_uses'        => 'nullable|integer|min:0',
            'status'          => 'required|in:draft,active,paused,expired,cancelled',
            'requires_approval'=> 'nullable|boolean',
            'terms_en'        => 'nullable|string',
            'terms_ar'        => 'nullable|string',
        ]);

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

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

        // Re-link membership types
        $this->db()->delete('special_offer_membership_types', 'offer_id = ?', [$id]);
        $mtIds = $request->post('membership_type_ids', []);
        if (is_array($mtIds)) {
            foreach ($mtIds as $mtId) {
                $this->db()->insert('special_offer_membership_types', ['offer_id' => $id, 'membership_type_id' => (int) $mtId]);
            }
        }

        $this->audit('update', 'special_offers', $id, 'Updated offer: ' . $data['offer_code'], $old, $data);
        $this->json(['success' => true, 'message' => lang('board.offer_updated'), 'redirect' => '/offers/' . $id]);
    }

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

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

        if ($offer['max_uses'] && $offer['current_uses'] >= $offer['max_uses']) {
            $this->json(['success' => false, 'message' => 'Offer has reached maximum uses'], 400);
            return;
        }

        $memberId = (int) $request->post('member_id');
        $discountAmount = (float) $request->post('discount_amount', 0);
        $invoiceId = $request->post('invoice_id') ? (int) $request->post('invoice_id') : null;

        $this->db()->insert('member_applied_offers', [
            'member_id' => $memberId,
            'offer_id' => $id,
            'invoice_id' => $invoiceId,
            'applied_date' => date('Y-m-d'),
            'discount_amount' => $discountAmount,
            'approved_by' => auth_id(),
            'notes' => $request->post('notes', ''),
        ]);

        $this->db()->update('special_offers', [
            'current_uses' => $offer['current_uses'] + 1,
        ], 'id = ?', [$id]);

        $this->audit('execute', 'member_applied_offers', null, "Applied offer {$offer['offer_code']} to member {$memberId}");
        $this->json(['success' => true, 'message' => lang('board.offer_applied')]);
    }
}