<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Carbon\Carbon;
use App\Models;
use App\Http\Requests;
use App\Libs\PaperLessNgx;
use App\Jobs\SendNewUssdClientEmail;
use App\Jobs\SendOnboardingCompletedEmailAlert;
use App\Jobs\SendShortCodeListToFinance;
use App\Jobs\SendNewNotesEmailAlert;
use Spatie\Activitylog\Models\Activity;
use Illuminate\Support\Facades\Config;

class ClientsController extends Controller
{
    public function index(): View
    {        
        return view('client.index-tabulator', [
            'page_title' => 'Clients',
            'current_user' => session('current_user')
        ]);
    }

    public function indexInactive(): View
    {
        return view('client.index-inactive', [
            'page_title' => 'Inactive Clients',
            'current_user' => session('current_user')
        ]);
    }

    public function indexStatus($status): View
    {
        return view('client.index-status', [
            'status' => $status,
            'page_title' => strtoupper($status) . ' Clients',
            'current_user' => session('current_user')
        ]);
    }

    public function indexCancelled(): View
    {
        return view('client.index-prospective', [
            'page_title' => 'Prospective Clients',
            'current_user' => session('current_user')
        ]);
    }

    public function indexDiscussion(): View
    {
        return view('client.index-prospective', [
            'page_title' => 'In Discussion Clients',
            'current_user' => session('current_user')
        ]);
    }

    public function getClientJson(Request $request): JsonResponse
    {
        $query = DB::table('clients')
            ->join('auth_users AS aumngr', 'aumngr.id', '=', 'clients.auth_user_id')
            ->join('auth_users AS aumodify', 'aumodify.id', '=', 'clients.last_modified_by')
            ->join('flags AS flags', 'flags.country', '=', 'clients.country')
            ->select('clients.id', 'clients.name', 'clients.status', 'clients.progress_indicator_score', 'clients.country', 'aumngr.name As accountMgr', 'aumodify.name AS modifiedBy', 'flags.url AS theflag')
            ->whereNotIn('status', ['inactive', 'Cancelled']);

        if ($request->filled('keyword')) {
            $keyword = $request->keyword;
            $query->where(function ($q) use ($keyword) {
                $q->where('clients.name', 'LIKE', "%{$keyword}%")
                  ->orWhere('clients.country', 'LIKE', "%{$keyword}%")
                  ->orWhere('aumngr.name', 'LIKE', "%{$keyword}%")
                  ->orWhere('aumodify.name', 'LIKE', "%{$keyword}%");
            });
        }

        return response()->json($query->orderBy('name', 'ASC')->get());
    }

    public function getInactiveClientJson(Request $request): JsonResponse
    {
        $query = DB::table('clients')
            ->join('auth_users AS aumngr', 'aumngr.id', '=', 'clients.auth_user_id')
            ->join('auth_users AS aumodify', 'aumodify.id', '=', 'clients.last_modified_by')
            ->join('flags AS flags', 'flags.country', '=', 'clients.country')
            ->select('clients.id', 'clients.name', 'clients.status', 'clients.progress_indicator_score', 'clients.country', 'aumngr.name As accountMgr', 'aumodify.name AS modifiedBy', 'flags.url AS theflag')
            ->whereIn('status', ['inactive', 'Cancelled']);

        if ($request->filled('keyword')) {
            $keyword = $request->keyword;
            $query->where(function ($q) use ($keyword) {
                $q->where('clients.name', 'LIKE', "%{$keyword}%")
                  ->orWhere('clients.status', 'LIKE', "%{$keyword}%")
                  ->orWhere('clients.country', 'LIKE', "%{$keyword}%")
                  ->orWhere('aumngr.name', 'LIKE', "%{$keyword}%")
                  ->orWhere('aumodify.name', 'LIKE', "%{$keyword}%")
                  ->orWhere('clients.progress_indicator_score', 'LIKE', "%{$keyword}%");
            });
        }

        return response()->json($query->orderBy('name', 'ASC')->get());
    }

    public function create(): View
    {
        return view('client.create', [
            'page_title'    => 'Create Client',
            'countries'     => Models\Country::pluck('en_short_name', 'en_short_name'),
            'service_type'  => Models\Service::pluck('name', 'name'),
            'status'        => ['Live' => 'Live', 'Inactive' => 'Inactive', 'Prospective' => 'Prospective', 'Cancelled' => 'Cancelled'],
            'currency'      => Models\Currency::pluck('name', 'name'),
            'auth_users'    => Models\SystemUser::pluck('name', 'id'),
            'payment_type'  => ['Prepaid' => 'Prepaid', 'Postpaid' => 'Postpaid'],
            'company_types' => ['Aggregator/Supplier' => 'Aggregator/Supplier', 'Enterprise' => 'Enterprise', 'Hybrid' => 'Hybrid'],
            'industries'    => Models\Industry::orderBy('name', 'ASC')->pluck('name', 'name')
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name'         => 'required|unique:clients,name',
            'email'        => 'required|email',
            'services'     => 'required|array',
            'country'      => 'required',
            'status'       => 'required',
            'payment_mode' => 'required',
            'currency'     => 'required',
            'company_type' => 'required',
            'industry'     => 'required',
            'auth_user_id' => 'required',
        ]);

        $onboarding_stages = Models\ClientOnboardingMainStage::orderBy('stage_id')->get();
        $client_current_stages = [];

        foreach ($onboarding_stages as $value) {
            $client_current_stages[$value->stage] = "PENDING";
        }

        $client_arr = [
            'name'                      => $request->name,
            'email'                     => $request->email,
            'country'                   => $request->country,
            'status'                    => $request->status,
            'pay_mode'                  => $request->payment_mode,
            'currency'                  => $request->currency,
            'auth_user_id'              => $request->auth_user_id,
            'created_by'                => session('current_user.id'),
            'last_modified_by'          => session('current_user.id'),
            'progress_indicator_score'  => 10,
            'progress_indicator'        => $onboarding_stages[0]->stage,
            'onboarding_progress_stage' => json_encode($client_current_stages),
            'notes'                     => $request->notes,
            'services'                  => json_encode($request->services),
            'phone'                     => $request->phone,
            'skype_name'                => $request->skype_name,
            'linkedin_name'             => $request->linkedin_name,
            'contact_person'            => $request->contact_person,
            'company_type'              => $request->company_type,
            'industry'                  => $request->industry,
        ];

        $result = Models\Client::create(array_filter($client_arr)); // Remove nulls automatically

        $get_stage_subs_items = Models\ClientOnboardingSubItem::get();
        foreach ($get_stage_subs_items as $value) {
            Models\ClientOnboardingProgress::create([
                'stage_id'  => $value->stage_id,
                'client_id' => $result->id,
                'name'      => $value->name,
                'status'    => 'PENDING'
            ]);
        }

        if (in_array('USSD', $request->services)) {
            Log::info('ussd client detected');
            Models\UssdClientPayment::create([
                'client_id'           => $result->id,
                'last_modified_by_id' => session('current_user.id')
            ]);
        }

        Models\UserActivity::create([
            'type'       => 'staff',
            'content'    => session('current_user.name') . " added a new client ({$result->name}) successfully!",
            'user_id'    => session('current_user.id'),
            'ip_address' => request()->ip(),
            'device'     => $request->header('User-Agent')
        ]);

        Session::flash('success_message', 'Client successfully added');
        return redirect('clients');
    }

    public function show($id): View
    {
        $showclient = Models\Client::with('service_info', 'country_flag_info', 'auth_user_info', 'short_code_info')->findOrFail($id);

        $networks_raw = [
            'AirtelTigo GH', 'MTN GH', 'Airtel MW', 'Airtel Zambia', 'TNM MW',
            'Safaricom Kenya', 'Airtel Kenya', 'Telkom Kenya', 'Orange Kenya'
        ];
        sort($networks_raw);

        $renewal_due = 'N/A';
        $highlight_colour = 'none';

        if (!empty($showclient->contract_validity)) {
            $expiry_date = Carbon::parse($showclient->contract_validity);
            $current_date = Carbon::today();
            $days = $current_date->diffInDays($expiry_date, false); // False allows negative values for past dates

            if ($days < 0) {
                $highlight_colour = 'warning';
                $days_abs = abs($days);
                if ($days_abs > 365) $renewal_due = "Contract expired " . floor($days_abs / 365) . " year(s) ago";
                elseif ($days_abs > 31) $renewal_due = "Contract expired " . floor($days_abs / 31) . " month(s) ago";
                else $renewal_due = "Contract expired {$days_abs} days(s) ago";
            } else {
                if ($days > 365) $renewal_due = "In " . floor($days / 365) . " year(s)";
                elseif ($days > 31) $renewal_due = "In " . floor($days / 31) . " months";
                else $renewal_due = "In {$days} day(s)";
            }
        }

        $change_account_mgr_permission = Config::get('permissions.CHANGE_ACCOUNT_MANAGERS');
        $has_permission = $this->hasAnyAccess([$change_account_mgr_permission]) ? 'YES' : 'NO';

        return view('client.show_accordion', [
            'page_title'             => 'Client Profile',
            'showclient'             => $showclient,
            'show_services'          => Models\ClientCategory::where('client_id', $id)->get(),
            'service_type'           => Models\Service::pluck('name', 'id'),
            'service_type_names'     => Models\Service::pluck('name', 'name'),
            'show_notes'             => Models\ClientNote::with('created_by_info', 'client_info')->where('client_id', $id)->latest()->take(20)->get(),
            'show_notes_highlight'   => Models\ClientNote::with('created_by_info', 'client_info')->where('client_id', $id)->where('highlight', 'YES')->latest()->take(1)->get(),
            'status_bg'              => $showclient->status == 'Live' ? 'info' : ($showclient->status == 'Prospective' ? 'warning' : 'danger'),
            'progress_status_bg'     => $showclient->progress_indicator_score >= 70 ? 'success' : ($showclient->progress_indicator_score >= 50 ? 'warning' : 'danger'),
            'voice_codes'            => Models\ClientShortCode::where('client_id', $id)->where('code_type', 'voice')->get(),
            'sms_codes'              => Models\ClientShortCode::where('client_id', $id)->where('code_type', 'sms')->get(),
            'ussd_codes'             => Models\ClientShortCode::where('client_id', $id)->where('code_type', 'ussd')->get(),
            'countries'              => Models\Country::pluck('en_short_name', 'en_short_name'),
            'networks'               => Models\NetworkOps::pluck('name', 'id'),
            'progress_indicators'    => Models\ClientIndicator::pluck('name', 'name'),
            'networks_raw'           => array_combine($networks_raw, $networks_raw),
            'renewal_due'            => $renewal_due,
            'recent_payments'        => Models\ClientPayment::where('client_id', $id)->latest()->get(),
            'highlight_colour'       => $highlight_colour,
            'showdocuments'          => Models\ClientFile::where('client_id', $id)->get(),
            'support_fees'           => Models\ClientSupportFees::where('client_id', $id)->latest()->get(),
            'recurring_arr'          => ['NO' => 'NO', 'Monthly' => 'Monthly', 'Quarterly' => 'Quarterly', 'Semiannual' => 'Semiannual', 'Yearly' => 'Yearly'],
            'change_account_mgr_permisson' => $has_permission,
            'am_list_arr'            => Models\SystemUser::orderBy('name', 'ASC')->pluck('name', 'id'),
            'country_network_arr'    => DB::table('network_operators')->selectRaw('id, concat(name, " (", country, ")") AS network')->orderBy('network')->pluck('network', 'network'),
            'mnos_arr'               => ['' => '-- Select Country first --']
        ]);
    }

    public function update(Requests\UpdateClientRequest $request, $id): RedirectResponse
    {
        $client_update = Models\Client::findOrFail($id);
        $paperless = new PaperLessNgx();

        if ($client_update->progress_indicator != 'COMPLETED') {
            $current_pending_stage_details = Models\ClientOnboardingMainStage::where('stage', $request->current_pending_stage)->first();
            $get_stage_subs_items = Models\ClientOnboardingSubItem::where('stage_id', $current_pending_stage_details->stage_id)->get();
            
            if ($request->onboarding_sub_items_progress) {
                foreach ($request->onboarding_sub_items_progress as $value) {
                    Models\ClientOnboardingProgress::updateOrCreate(
                        ['stage_id' => $current_pending_stage_details->stage_id, 'client_id' => $id, 'name' => $value],
                        ['status' => 'COMPLETED']
                    );
                }
            }

            $get_stage_onboarding_status = Models\ClientOnboardingProgress::where('client_id', $id)
                ->where('stage_id', $current_pending_stage_details->stage_id)
                ->where('status', 'COMPLETED')
                ->get();
                
            $onboarding_progress_stage = json_decode($client_update->onboarding_progress_stage, true);
            
            if (count($get_stage_subs_items) == count($get_stage_onboarding_status)) {
                $onboarding_progress_stage[$current_pending_stage_details->stage] = 'COMPLETED';
            }

            $pending_stage = Arr::where($onboarding_progress_stage, fn($value) => $value == "PENDING");

            if (!empty($pending_stage)) {
                $client_update->progress_indicator = array_key_first($pending_stage);
            } else {
                $client_update->progress_indicator = 'COMPLETED';
                dispatch(new SendOnboardingCompletedEmailAlert(Models\Client::with('auth_user_info')->find($id)));
            }
        }

        // File handling logic encapsulated safely
        $fileFields = [
            'document_one' => 'document_one_name',
            'document_two' => 'document_two_name',
            'document_three' => 'document_three_name',
            'other_document' => 'other_document_name'
        ];

        foreach ($fileFields as $fileInput => $nameInput) {
            if ($request->hasFile($fileInput) && $request->file($fileInput)->isValid() && $request->filled($nameInput)) {
                $filename = "erp_" . time() . Str::random(4) . "." . $request->file($fileInput)->extension();
                $request->file($fileInput)->storeAs('client_files', $filename, 'public');

                $document_name = $fileInput === 'other_document' && !$request->filled($nameInput) 
                                 ? 'Other Document' 
                                 : $request->input($nameInput);

                Models\ClientFile::updateOrCreate(
                    ['client_id' => $id, 'name' => $document_name],
                    [
                        'file_path' => $filename,
                        'file_extension' => $request->file($fileInput)->extension(),
                        'file_reff' => time() . uniqid(),
                        'created_by' => session('current_user.id'),
                    ]
                );
            }
        }

        $client_update->name = $request->name;
        $client_update->email = $request->email;
        $client_update->phone = $request->phone ?? "";
        $client_update->contact_person = $request->contact_person;
        $client_update->status = $request->status;
        $client_update->pay_mode = $request->payment_mode;
        $client_update->country = $request->country;
        $client_update->currency = $request->currency;
        $client_update->notes = $request->notes;
        $client_update->industry = $request->industry;

        if ($client_update->progress_indicator != 'COMPLETED') {
            $client_update->onboarding_progress_stage = json_encode($onboarding_progress_stage);
            $progress_breakdown = array_count_values($onboarding_progress_stage);
            
            $indicator_score = Arr::has($progress_breakdown, 'COMPLETED') 
                               ? ($progress_breakdown['COMPLETED'] / count($onboarding_progress_stage)) * 100 
                               : 0;

            $client_update->progress_indicator_score = number_format($indicator_score);
        } else {
            $client_update->progress_indicator_score = 100;
        }

        $client_update->skype_name = $request->skype_name ?? "";
        $client_update->linkedin_name = $request->linkedin_name ?? "";
        $client_update->smpp_username = $request->smpp_username ?? "";
        $client_update->company_type = $request->company_type ?? "";
        $client_update->auth_user_id = $request->auth_user_id ?? "";
        $client_update->contract_type = $request->contract_type ?? "";
        $client_update->contract_validity = $request->contract_validity ?? "";
        $client_update->contract_auto_renew = $request->contract_auto_renew ?? "";
        $client_update->sender_ids = $request->sender_ids ? json_encode($request->sender_ids) : "";
        $client_update->connections = $request->connections ? json_encode($request->connections) : "";
        $client_update->services = $request->services ? json_encode($request->services) : "";
        $client_update->message_types = $request->message_types ? json_encode($request->message_types) : "";
        $client_update->finance_email = $request->finance_email ? json_encode($request->finance_email) : "";
        $client_update->support_emails = $request->support_emails ? json_encode($request->support_emails) : "";
        $client_update->rate_emails = $request->rate_emails ? json_encode($request->rate_emails) : "";
        $client_update->support_phones = $request->support_phones ? json_encode($request->support_phones) : "";
        $client_update->support_skype = $request->support_skype ? json_encode($request->support_skype) : "";
        
        if ($request->has('how_we_got_client')) {
            $client_update->how_we_got_client = $request->how_we_got_client == 'Other' ? ($request->how_we_got_client_other ?? "") : $request->how_we_got_client;
        }

        $client_update->last_modified_by = session('current_user.id');
        $client_update->save();

        Models\UserActivity::create([
            'type' => 'staff',
            'content' => session('current_user.name') . " updated ({$client_update->name}) details successfully!",
            'user_id' => session('current_user.id'),
            'ip_address' => request()->ip(),
            'device' => $request->header('User-Agent')
        ]);

        Session::flash('success_message', 'Client successfully Updated');
        return redirect(url('clients', $id));
    }

    public function getClientFile($id)
    {
        $client_file = Models\ClientFile::with('client_info')->findOrFail($id);
        
        // Use proper storage path logic
        $file = storage_path('app/public/client_files/' . $client_file->file_path);

        if (!file_exists($file)) {
            abort(404, 'File not found on the server.');
        }

        $filename = Str::slug($client_file->client_info->name . "_" . $client_file->name, '_');
        $filename = $filename . "." . $client_file->file_extension;

        return Response::download($file, $filename);
    }

    public function cleanStr($string): string
    {
        // Replaced custom regex block with Laravel's native slug helper
        return Str::slug($string, '_');
    }
    
    // ... Additional unchanged methods (getMnoCountry, etc.) follow below.
}