<?php

namespace App\Controllers\Admin;

use App\Models\Control\PlanModel;

class PlanController extends BaseAdminController
{
    public function index()
    {
        $plans = new PlanModel();

        return view('admin/plans/index', [
            'pageTitle' => 'Plans & Pricing',
            'activeNav' => 'plans',
            'plans'     => $plans->orderBy('sort_order', 'asc')->findAll(),
        ]);
    }

    public function new()
    {
        return view('admin/plans/form', [
            'pageTitle' => 'New Plan',
            'activeNav' => 'plans',
            'plan'      => null,
        ]);
    }

    public function create()
    {
        return $this->save(new PlanModel());
    }

    public function edit(int $id)
    {
        $plan = (new PlanModel())->find($id);

        if ($plan === null) {
            return redirect()->to('/admin/plans')->with('error', 'Plan not found.');
        }

        return view('admin/plans/form', [
            'pageTitle' => 'Edit Plan',
            'activeNav' => 'plans',
            'plan'      => $plan,
        ]);
    }

    public function update(int $id)
    {
        $plans = new PlanModel();
        $plan  = $plans->find($id);

        if ($plan === null) {
            return redirect()->to('/admin/plans')->with('error', 'Plan not found.');
        }

        return $this->save($plans, $id);
    }

    private function save(PlanModel $plans, ?int $id = null)
    {
        $features = array_filter(array_map('trim', explode("\n", (string) $this->request->getPost('features'))));

        $data = [
            'name'             => $this->request->getPost('name'),
            'slug'             => $this->request->getPost('slug'),
            'price'            => parse_money($this->request->getPost('price')),
            'billing_interval' => $this->request->getPost('billing_interval'),
            'max_rooms'        => $this->request->getPost('max_rooms') ?: null,
            'description'      => $this->request->getPost('description'),
            'features'         => $plans->encodeFeatures($features),
            'is_active'        => $this->request->getPost('is_active') ? 1 : 0,
            'sort_order'       => (int) ($this->request->getPost('sort_order') ?: 0),
        ];

        $ok = $id === null ? $plans->insert($data) : $plans->update($id, $data);

        if ($ok === false) {
            return $this->redirectWithModelErrors($plans);
        }

        $this->logAdminActivity('plans', ($id === null ? 'Created' : 'Updated') . " plan \"{$data['name']}\".");

        return redirect()->to('/admin/plans')->with('success', 'Plan saved.');
    }

    public function toggleActive(int $id)
    {
        $plans = new PlanModel();
        $plan  = $plans->find($id);

        if ($plan === null) {
            return redirect()->to('/admin/plans')->with('error', 'Plan not found.');
        }

        $plans->update($id, ['is_active' => $plan->is_active ? 0 : 1]);

        $this->logAdminActivity('plans', ($plan->is_active ? 'Deactivated' : 'Activated') . " plan \"{$plan->name}\".");

        return redirect()->to('/admin/plans')->with('success', 'Plan updated.');
    }
}
