<?php

namespace App\Http\Controllers;

use App\Helper\Helper;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Session;
use App\Exports\EligibleLendersExport;
use Maatwebsite\Excel\Facades\Excel;

class FcsController extends Controller
{

    public function index(Request $request,$id)
{
    //dd($id);
    // $bankName = $request->query('bank_name'); // Use query() for GET parameters
$lead_id=$id;
    //dd($lead_id);

    $url = env('API_URL') . 'fcs/' . $lead_id;   
    $response = Helper::GetApi($url);
    $fcs_data = $response->data;
    $url = env('API_URL') . 'lender-matrix/' . $lead_id;   
    $response1 = Helper::GetApi($url);
     $lender_data = $response1->data;
    //echo "<pre>";print_r($lender_data);die;

    return view("leads.fcs-data", compact('fcs_data','lead_id','lender_data'));
}

    public function store(Request $request,$id)
    {
        // Get all input data
        $data = $request->all();
        $tabNumber = $data['tabNumber'] ?? '';
        $bank_id = $request->input('bank_id');
        $lead_id = $id;

        //dd($bank_id);
        
        // Check if the new format is being used (with 'data' and 'bank_name' inside it)
        if (isset($data['data']) && isset($data['data']['bank_name'])) {
            // Extract the bank name and monthly data from the new format
            $bank_name = $data['data']['bank_name'];
            $monthly_data = $data['data'];
            
            // Remove 'bank_name' from the monthly data since it's not part of month data
            unset($monthly_data['bank_name']);
            
            // Prepare the data to send to the API
            $url = env('API_URL') . 'fcs-lendor';
            $body = [
                'id' => Session::get('id'),
                'token' => Session::get('tokenId'),
                'bank_name' => $bank_name, // Include the bank name from the new format
                'monthly_data' => $monthly_data, // Include the remaining monthly data
                'bank_id'=>$tabNumber,
                'lead_id'=>$lead_id,
            ];
            //dd($body);
            
            try {
                $ext_group = Helper::PostApi($url, $body);
                //echo "<pre>";print_r($ext_group);die;

                if ($ext_group->success == 'true') {
                    return response()->json(['success' => true, 'message' => $ext_group->message]);
                }
    
                if ($ext_group->success == 'false') {
                    return response()->json(['success' => false, 'message' => $ext_group->message]);
                }
            } catch (BadResponseException $e) {
                return back()->with('message', "Error code - (edit-campaign): Oops something went wrong :( Please contact your administrator.)");
            } catch (RequestException $ex) {
                return back()->with('message', "Error code - (edit-campaign): Oops something went wrong :( Please contact your administrator.)");
            }
        } else {
            // Fallback to the old format handling
            $months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
            $organizedData = [];
    
            foreach ($months as $month) {
                $deposit1 = $data['deposit1'][$month] ?? null;
                $adjustment = $data['adjustment'][$month] ?? null;
                $adb = $data['adb'][$month] ?? null;
                $deposit2 = $data['deposit2'][$month] ?? null;
                $nsfs = $data['nsfs'][$month] ?? null;
                $negatives = $data['negatives'][$month] ?? null;
                $ending_balance = $data['ending-balance'][$month] ?? null;
    
                $organizedData[$month] = [
                    'deposit1' => $deposit1,
                    'adjustment' => $adjustment,
                    'revenue' => is_null($deposit1) || is_null($adjustment) ? null : ($deposit1 - $adjustment),
                    'adb' => $adb,
                    'deposit2' => $deposit2,
                    'nsfs' => $nsfs,
                    'negatives' => $negatives,
                    'ending_balance' => $ending_balance,
                ];
            }
    
            // Prepare the data to send to the API (old format)
            $url = env('API_URL') . 'fcs-lendor';
            $body = [
                'id' => Session::get('id'),
                'token' => Session::get('tokenId'),
                'bank_name' => $request->input('bank_name'), // Bank name from the old format
                'monthly_data' => $organizedData,
                'bank_id'=>$bank_id,
                'lead_id'=>$lead_id,

            ];
    
            try {
                $ext_group = Helper::PostApi($url, $body);
    
                if ($ext_group->success == 'true') {
                    return back()->withSuccess($ext_group->message);
                }
    
                if ($ext_group->success == 'false') {
                    return back()->withSuccess($ext_group->message);
                }
            } catch (BadResponseException $e) {
                return back()->with('message', "Error code - (edit-campaign): Oops something went wrong :( Please contact your administrator.)");
            } catch (RequestException $ex) {
                return back()->with('message', "Error code - (edit-campaign): Oops something went wrong :( Please contact your administrator.)");
            }
        }
    }
    
    
    public function store1(Request $request)
    {
        // Get all input data
        $data = $request->all();

        // Define months
        $months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
        $organizedData = [];
    
        foreach ($months as $month) {
            // Ensure all required keys exist before accessing them
            $deposit1 = $data['deposit1'][$month] ?? null;
            $adjustment = $data['adjustment'][$month] ?? null;
            $adb = $data['adb'][$month] ?? null;
            $deposit2 = $data['deposit2'][$month] ?? null;
            $nsfs = $data['nsfs'][$month] ?? null;
            $negatives = $data['negatives'][$month] ?? null;
            $ending_balance = $data['ending-balance'][$month] ?? null; // Fix the key name to match with incoming data
            
            // Check if the necessary keys have values (not null)
            if (!is_null($deposit1) && !is_null($adjustment) && !is_null($adb) && !is_null($deposit2) && !is_null($nsfs) && !is_null($negatives) && !is_null($ending_balance)) {
                $organizedData[$month] = [
                    'deposit1' => $deposit1,
                    'adjustment' => $adjustment,
                    'revenue' => $deposit1 - $adjustment,
                    'adb' => $adb,
                    'deposit2' => $deposit2,
                    'nsfs' => $nsfs,
                    'negatives' => $negatives,
                    'ending_balance' => $ending_balance,
                ];
            } else {
                // Handle missing month data as needed
                $organizedData[$month] = [
                    'deposit1' => $deposit1,
                    'adjustment' => $adjustment,
                    'revenue' => is_null($deposit1) || is_null($adjustment) ? null : ($deposit1 - $adjustment),
                    'adb' => $adb,
                    'deposit2' => $deposit2,
                    'nsfs' => $nsfs,
                    'negatives' => $negatives,
                    'ending_balance' => $ending_balance,
                ];
            }
        }
         //dd($organizedData);

        // Prepare the data to send to the API
        $url = env('API_URL') . 'fcs-lendor';
        $body = [
            'id' => Session::get('id'),
            'token' => Session::get('tokenId'),
            'bank_name' => $request->input('bank_name'),
            'monthly_data' => $organizedData // Include the organized data here
        ];
    
        try {
            $ext_group = Helper::PostApi($url, $body);
           //echo "<pre>";print_r($ext_group);die;

            if ($ext_group->success == 'true') {
                return back()->withSuccess($ext_group->message);
            }
    
            if ($ext_group->success == 'false') {
                return back()->withSuccess($ext_group->message);
            }
        } catch (BadResponseException $e) {
            return back()->with('message', "Error code - (edit-campaign): Oops something went wrong :( Please contact your administrator.)");
        } catch (RequestException $ex) {
            return back()->with('message', "Error code - (edit-campaign): Oops something went wrong :( Please contact your administrator.)");
        }
    }
    

 public function EligibleLender(Request $request,$lead_id,$bank_id)
 {
    //dd($bank_id);
    $lenders=[];
    $response=[];
    $url = env('API_URL') . 'eligible-lender/'. $lead_id . '/' . $bank_id;;   
    $response = Helper::GetApi($url);
    if (isset($response->data)) {
        $lenders = $response->data;
    }
    //echo "<pre>";print_r($lenders);die;
       // Check if download is requested
       if ($request->has('download') && $request->get('download') == 'excel') {
        return Excel::download(new EligibleLendersExport($lenders), 'eligible-lenders.xlsx');
    }
    return view('leads.eligible_lender',compact('lenders','lead_id','bank_id'));

 }


public function LenderList(Request $request,$lead_id,$bank_id){

//    dd($request->all());

   $url = env('API_URL') . 'lender-matrix/' . $lead_id .'/'. $bank_id;
   $body = [
    'id' => Session::get('id'),
    'token' => Session::get('tokenId'),
    'lender_name'=>$request->input('lender_name'),
    'funding_date'=>$request->input('funding_date'),
    'net'=>$request->input('net'),
    'funding'=>$request->input('funding'),
    'funding_factor'=>$request->input('funding_factor'),
    'weekly'=>$request->input('weekly'),
    'daily'=>$request->input('daily'),
    'balance'=>$request->input('balance'),
    'days'=>$request->input('days'),
    'withhold'=>$request->input('withhold'),
    'end_date'=>$request->input('end_date'),
    'transfer_accounts'=>$request->input('transfer_accounts'),
    'notes'=>$request->input('notes'),
    'bank_id'=>$bank_id,
    'lead_id'=>$lead_id,

];
//dd($body);
   $response = Helper::PostApi($url,$body);

   if ($response && isset($response->data)) {
    // Redirect back with a success message
    return redirect()->back()->with('success', 'Data saved successfully!');
} else {
    // Redirect back with an error message if response is empty or failed
    return redirect()->back()->with('error', 'Failed to save data.');
}
}





}

