<?php

namespace Licenzo\Http\Controller\Api\V1;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

use Licenzo\Framework\Http\Request;
use Licenzo\Http\Traits\HandlesErrors;
use Licenzo\Model\License;
use Licenzo\Model\LicenseActivation;
use Licenzo\Model\Product;
use Licenzo\Model\ProductVariation;
use Licenzo\Services\LicenseService;

class LicenseActivationController
{
    use HandlesErrors;

    protected $licenseService;
    public function __construct(LicenseService $licenseService)
    {
        $this->licenseService = $licenseService;
    }

    public function activate(Request $request, $license, $product, $variation)
    {
        try {
            // Find license by key
            $license = License::where('license_key', $license)->first();
            if (!$license) {
                return ["success" => false, "message" => __("License not found", 'licenzo')];
            }

            // Find product and variation
            $product = Product::where('uuid', $product)->first();
            $variation = ProductVariation::where('uuid', $variation)->first();
            if (!$product || !$variation) {
                return ["success" => false, "message" => __("Product or Variation not found", 'licenzo')];
            }

            // Activate the license
            $activationData = $request->getSafe([
                'instance_identifier' => 'sanitize_text_field',
                'activation_method'   => 'sanitize_text_field',
                'fingerprint'         => 'sanitize_text_field',
                'domain'              => 'sanitize_text_field',
                'meta'                => null,
            ]);
            // Sanitize meta array if present
            if (is_array($activationData['meta'] ?? null)) {
                $activationData['meta'] = array_map('sanitize_text_field', $activationData['meta']);
            }
            $activation = $this->licenseService->activateLicense($license, $product, $variation, $activationData);

            return ["success" => true, "message" => __("License activated", 'licenzo'), "data" => $this->response($license, $activation)];
        } catch (\Throwable $th) {
            return $this->handleError($th, 'Activation failed', 403);
        }
    }

    public function check(Request $request, $license, $product, $variation)
    {
        try {
            // Find license by key
            $license = License::where('license_key', $license)->first();
            if (!$license) {
                return ["success" => false, "message" => __("License not found", 'licenzo')];
            }

            // Find product and variation
            $product = Product::where('uuid', $product)->first();
            $variation = ProductVariation::where('uuid', $variation)->first();
            if (!$product || !$variation) {
                return ["success" => false, "message" => __("Product or Variation not found", 'licenzo')];
            }

            $checkData = $request->getSafe([
                'instance_identifier' => 'sanitize_text_field',
                'activation_hash'     => 'sanitize_text_field',
            ]);
            $activation = $this->licenseService->checkLicense($license, $product, $variation, $checkData);

            if ($activation) {
                return ["success" => true, "message" => __("License is valid", 'licenzo'), "data" => $this->response($license, $activation)];
            } else {
                return ["success" => false, "message" => __("License is invalid", 'licenzo')];
            }
        } catch (\Throwable $th) {
            return $this->handleError($th, 'Validation failed', 403);
        }
    }

    public function deactivate(Request $request, $license, $product, $variation)
    {
        try {
            // Find license by key
            $license = License::where('license_key', $license)->first();
            if (!$license) {
                return ["success" => false, "message" => __("License not found", 'licenzo')];
            }

            // Find product and variation
            $product = Product::where('uuid', $product)->first();
            $variation = ProductVariation::where('uuid', $variation)->first();
            if (!$product || !$variation) {
                return ["success" => false, "message" => __("Product or Variation not found", 'licenzo')];
            }

            // Deactivate the license
            $deactivationData = $request->getSafe([
                'instance_identifier' => 'sanitize_text_field',
            ]);
            $result = $this->licenseService->deactivateLicense($license, $product, $variation, $deactivationData);
            if ($result) {
                return ["success" => true, "message" => __("License deactivated", 'licenzo')];
            } else {
                return ["success" => false, "message" => __("No active activation found", 'licenzo')];
            }
        } catch (\Throwable $th) {
            return $this->handleError($th, 'Deactivation failed', 403);
        }
    }

    private function response(License $license, ?LicenseActivation $activation = null)
    {
        if ($activation) {
            return [
                'activation_hash' => $activation->activation_hash,
                'support_end_date' => $license->support_till ? gmdate('Y-m-d H:i:s', strtotime($license->support_till)) : null,
                'valid_till' => $license->expire_date ? gmdate('Y-m-d H:i:s', strtotime($license->expire_date)) : null,
                'status' => $license->status,
                'is_trial' => $license->is_trial,
                'is_lifetime' => $license->expire_date === null,
            ];
        } else {
            return null;
        }
    }
}
