<?php

namespace App\Http\Controllers;

use App\Models\Subscription;
use App\Models\Customer;
use App\Services\WhmcsService;
use Illuminate\Http\Request;

class SubscriptionController extends Controller
{
    public function index()
    {
        $subscriptions = Subscription::with('customer')->latest()->paginate(15);
        return view('accounting.subscriptions.index', compact('subscriptions'));
    }

    public function create()
    {
        $customers = Customer::all();
        return view('accounting.subscriptions.create', compact('customers'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'customer_id' => 'required|exists:customers,id',
            'service_name' => 'required|string|max:255',
            'price' => 'required|numeric|min:0',
            'currency' => 'required|in:EGP,USD',
            'billing_cycle' => 'required|string',
            'start_date' => 'nullable|date',
            'next_due_date' => 'nullable|date',
        ]);

        Subscription::create($validated);
        return redirect()->route('accounting.subscriptions.index')->with('success', 'Subscription created successfully.');
    }

    public function edit(Subscription $subscription)
    {
        $customers = Customer::all();
        return view('accounting.subscriptions.edit', compact('subscription', 'customers'));
    }

    public function update(Request $request, Subscription $subscription)
    {
        $validated = $request->validate([
            'customer_id' => 'required|exists:customers,id',
            'service_name' => 'required|string|max:255',
            'price' => 'required|numeric|min:0',
            'currency' => 'required|in:EGP,USD',
            'billing_cycle' => 'required|string',
            'start_date' => 'nullable|date',
            'next_due_date' => 'nullable|date',
            'status' => 'required|in:active,suspended,cancelled',
        ]);

        $subscription->update($validated);
        return redirect()->route('accounting.subscriptions.index')->with('success', 'Subscription updated successfully.');
    }

    public function destroy(Subscription $subscription)
    {
        $subscription->delete();
        return back()->with('success', 'Subscription deleted successfully.');
    }

    /**
     * Sync subscriptions for a specific customer from WHMCS
     */
    public function sync(Customer $customer, WhmcsService $whmcs)
    {
        if (!$customer->whmcs_id) {
            return back()->with('error', 'Customer not linked to WHMCS.');
        }

        $response = $whmcs->getClientProducts($customer->whmcs_id);

        if (($response['result'] ?? '') !== 'success') {
            return back()->with('error', 'Failed to fetch products from WHMCS: ' . ($response['message'] ?? 'Unknown error'));
        }

        $products = $response['products']['product'] ?? [];
        $count = 0;

        foreach ($products as $p) {
            Subscription::updateOrCreate(
                ['whmcs_service_id' => $p['id']],
                [
                    'customer_id' => $customer->id,
                    'service_name' => $p['name'] . ' (' . $p['domain'] . ')',
                    'price' => floatval($p['recurringamount']),
                    'currency' => 'EGP', // Default, logic to detect currency needed if multi-currency
                    'billing_cycle' => $p['billingcycle'], // e.g., Monthly
                    'start_date' => $p['regdate'] ?: null,
                    'next_due_date' => ($p['nextduedate'] && $p['nextduedate'] != '0000-00-00') ? $p['nextduedate'] : null,
                    'status' => strtolower($p['status']),
                ]
            );
            $count++;
        }

        return back()->with('success', "Synced $count subscriptions from WHMCS.");
    }
}
