<?php

namespace App\Controllers\Admin;

use App\Models\Control\PlanModel;
use App\Models\Control\SubscriptionModel;
use App\Models\Control\TenantRecordModel;
use Config\Lookups;

/**
 * Assign/change a tenant's plan and move a subscription through its
 * status lifecycle. No dedicated index screen — subscriptions are always
 * viewed/managed from their tenant (see admin/tenants/show.php), the same
 * way rate plans are managed from a tenant's own settings rather than a
 * standalone list.
 */
class SubscriptionController extends BaseAdminController
{
    /**
     * Assigns a (possibly new) plan to a tenant. Always inserts a new row
     * — see CreateSubscriptionsTable for why history accumulates rather
     * than updating in place. A fresh assignment starts in `trial` status;
     * an operator flips it to `active` once the hotel has actually paid
     * (see updateStatus()) rather than this endpoint guessing.
     */
    public function assign(int $tenantId)
    {
        $tenants = new TenantRecordModel();
        $tenant  = $tenants->find($tenantId);

        if ($tenant === null) {
            return redirect()->to('/admin/tenants')->with('error', 'Hotel not found.');
        }

        $planId = (int) $this->request->getPost('plan_id');
        $plan   = (new PlanModel())->find($planId);

        if ($plan === null) {
            return redirect()->back()->with('error', 'Choose a valid plan.');
        }

        $subscriptions = new SubscriptionModel();
        $id = $subscriptions->insert([
            'tenant_id'             => $tenantId,
            'plan_id'               => $planId,
            'status'                => 'trial',
            'trial_ends_at'         => date('Y-m-d H:i:s', strtotime('+14 days')),
            'current_period_start'  => date('Y-m-d'),
            'current_period_end'    => date('Y-m-d', strtotime($plan->billing_interval === 'yearly' ? '+1 year' : '+1 month')),
        ], true);

        if ($id === false) {
            return $this->redirectWithModelErrors($subscriptions);
        }

        $this->logAdminActivity('subscriptions', "Assigned plan \"{$plan->name}\" to \"{$tenant->hotel_name}\".");

        return redirect()->to('/admin/tenants/' . $tenantId)->with('success', "Plan \"{$plan->name}\" assigned.");
    }

    public function updateStatus(int $id)
    {
        $subscriptions = new SubscriptionModel();
        $subscription  = $subscriptions->find($id);

        if ($subscription === null) {
            return redirect()->to('/admin/tenants')->with('error', 'Subscription not found.');
        }

        $status   = $this->request->getPost('status');
        $statuses = array_keys((new Lookups())->subscriptionStatuses);

        if (! in_array($status, $statuses, true)) {
            return redirect()->back()->with('error', 'Invalid status.');
        }

        $data = ['status' => $status];

        if ($status === 'cancelled') {
            $data['cancelled_at'] = date('Y-m-d H:i:s');
        }

        $subscriptions->update($id, $data);

        $tenant = (new TenantRecordModel())->find($subscription->tenant_id);
        $this->logAdminActivity('subscriptions', "Set subscription status to \"{$status}\" for \"{$tenant->hotel_name}\".");

        return redirect()->to('/admin/tenants/' . $subscription->tenant_id)->with('success', 'Subscription status updated.');
    }
}
