<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Sponsor;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\Hash;

class SponsorController extends Controller
{
    /**
     * List all sponsors with filters, search, and sorting.
     */
    public function index(Request $request)
    {
        $query = Sponsor::query();

        // Server-side Search
        if ($request->filled('search')) {
            $search = $request->input('search');
            $query->where(function($q) use ($search) {
                $q->where('full_name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%")
                  ->orWhere('mobile', 'like', "%{$search}%");
            });
        }

        // Server-side Status filter
        if ($request->filled('status') && $request->input('status') !== 'All') {
            $query->where('status', strtolower($request->input('status')));
        }

        // Server-side Location/City filter
        if ($request->filled('location') && $request->input('location') !== 'All') {
            $query->where('city', $request->input('location'));
        }

        // Server-side Sorting
        $sortField = $request->input('sort_field', 'created_at');
        $sortOrder = $request->input('sort_order', 'desc');
        if (in_array($sortField, ['full_name', 'email', 'city', 'status', 'created_at'])) {
            $query->orderBy($sortField, $sortOrder);
        } else {
            $query->orderBy('created_at', 'desc');
        }

        // Paginate
        $sponsors = $query->paginate(10)->withQueryString();

        return Inertia::render('Admin/Employers/Index', [
            'sponsors' => $sponsors,
            'filters' => $request->only(['search', 'status', 'location', 'sort_field', 'sort_order'])
        ]);
    }

    /**
     * Export sponsors as CSV with filters, search, and sorting.
     */
    public function export(Request $request)
    {
        $query = Sponsor::query();

        // Server-side Search
        if ($request->filled('search')) {
            $search = $request->input('search');
            $query->where(function($q) use ($search) {
                $q->where('full_name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%")
                  ->orWhere('mobile', 'like', "%{$search}%");
            });
        }

        // Server-side Status filter
        if ($request->filled('status') && $request->input('status') !== 'All') {
            $query->where('status', strtolower($request->input('status')));
        }

        // Server-side Location/City filter
        if ($request->filled('location') && $request->input('location') !== 'All') {
            $query->where('city', $request->input('location'));
        }

        // Server-side Sorting
        $sortField = $request->input('sort_field', 'created_at');
        $sortOrder = $request->input('sort_order', 'desc');
        if (in_array($sortField, ['full_name', 'email', 'city', 'status', 'created_at'])) {
            $query->orderBy($sortField, $sortOrder);
        } else {
            $query->orderBy('created_at', 'desc');
        }

        $sponsors = $query->get();

        $headers = [
            "Content-type"        => "text/csv",
            "Content-Disposition" => "attachment; filename=sponsors_export_" . date('Ymd_His') . ".csv",
            "Pragma"              => "no-cache",
            "Cache-Control"       => "must-revalidate, post-check=0, pre-check=0",
            "Expires"             => "0"
        ];

        $columns = ['ID', 'Full Name', 'Email', 'Mobile', 'City', 'Nationality', 'Address', 'Status', 'OTP Verified', 'Verified At', 'Subscription Plan', 'Subscription Status', 'Subscription Expiry', 'Created At'];

        $callback = function() use ($sponsors, $columns) {
            $file = fopen('php://output', 'w');
            fputcsv($file, $columns);

            foreach ($sponsors as $sponsor) {
                fputcsv($file, [
                    $sponsor->id,
                    $sponsor->full_name,
                    $sponsor->email,
                    $sponsor->mobile,
                    $sponsor->city ?? 'Dubai',
                    $sponsor->nationality ?? 'N/A',
                    $sponsor->address ?? 'N/A',
                    $sponsor->status,
                    $sponsor->is_verified ? 'Yes' : 'No',
                    $sponsor->otp_verified_at ? $sponsor->otp_verified_at->toDateTimeString() : 'N/A',
                    $sponsor->subscription_plan ?? 'None',
                    $sponsor->subscription_status ?? 'None',
                    $sponsor->subscription_end_date ? $sponsor->subscription_end_date->toDateString() : 'N/A',
                    $sponsor->created_at ? $sponsor->created_at->toDateTimeString() : 'N/A',
                ]);
            }

            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }

    /**
     * Approve and verify a sponsor.
     */
    public function verify($id)
    {
        $sponsor = Sponsor::findOrFail($id);
        $sponsor->update([
            'is_verified' => true,
            'otp_verified_at' => $sponsor->otp_verified_at ?? now(),
            'status' => 'active'
        ]);

        return back()->with('success', "Sponsor '{$sponsor->full_name}' verified and status activated successfully.");
    }

    /**
     * Suspend a sponsor.
     */
    public function suspend(Request $request, $id)
    {
        $sponsor = Sponsor::findOrFail($id);
        $sponsor->update([
            'status' => 'suspended'
        ]);

        return back()->with('success', "Sponsor '{$sponsor->full_name}' suspended successfully.");
    }

    /**
     * Activate a suspended/inactive sponsor.
     */
    public function activate($id)
    {
        $sponsor = Sponsor::findOrFail($id);
        $sponsor->update([
            'status' => 'active'
        ]);

        return back()->with('success', "Sponsor '{$sponsor->full_name}' activated successfully.");
    }

    /**
     * Delete a sponsor registry.
     */
    public function delete($id)
    {
        $sponsor = Sponsor::findOrFail($id);
        $name = $sponsor->full_name;
        $sponsor->delete();

        return back()->with('success', "Sponsor '{$name}' deleted successfully from database.");
    }

    /**
     * Edit / Update a sponsor's registry fields.
     */
    public function update(Request $request, $id)
    {
        $sponsor = Sponsor::findOrFail($id);
        $validated = $request->validate([
            'full_name' => 'required|string|max:255',
            'email' => 'required|email|unique:sponsors,email,' . $sponsor->id,
            'mobile' => 'required|string',
            'city' => 'required|string',
            'nationality' => 'nullable|string',
            'address' => 'nullable|string',
            'subscription_plan' => 'nullable|string',
            'subscription_status' => 'nullable|string',
        ]);

        $sponsor->update($validated);

        return back()->with('success', "Sponsor details saved successfully.");
    }
}
