<?php

namespace App\Http\Controllers\FCControllers;

use Illuminate\Http\Request;
use App\Models\fcmodels\Organization;
use App\Models\fcmodels\Organizationshortcode;
use App\Models\fcmodels\Currency_Expenditure;

use Auth;
use App\Models\fcmodels\AuditLog;
use App\Models\fcmodels\Wallet;

use Illuminate\Support\Facades\Http;

class OrganizationshortcodeContloller extends Controller
{
   
   
   
   protected $uri = 'http://www.mobisky.biz/api/mobisendsms.php';
    protected $smsApiUrl = 'https://mobisky.biz/api/mobisendsms.php';

public function shortcodesend(Request $request)
{
    // Validate the input
    $request->validate([
        'destination' => 'required',
        'message' => 'required',
    ]);

    // Capture and sanitize inputs
    $destination = substr(htmlspecialchars($request->input('destination'), ENT_QUOTES), -12);
    $message = htmlspecialchars($request->input('message'), ENT_QUOTES);

    // Log the inputs to verify they're captured
    \Log::info("Received Inputs - Destination: $destination, Message: $message");

    // Check if the values are empty and log an error if they are
    if (empty($destination) || empty($message)) {
        \Log::error("Empty destination or message. Check the form data submission.");
        return redirect()->back()->with('error', 'Failed to send message: Missing destination or message.');
    }

    // Initialize cURL
    $ch = curl_init();

    // Set cURL options
    curl_setopt($ch, CURLOPT_URL, $this->smsApiUrl); // Set the API endpoint
    curl_setopt($ch, CURLOPT_POST, true); // Set request method to POST
    curl_setopt($ch, CURLOPT_POSTFIELDS, [
        'username' => 'alitdigital',
        'password' => 'alitdigital',
        'destination' => $destination,
        'source' => '20384',
        'message' => $message,
        'shortcode' => '20384',
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Receive server response

    // Execute the cURL request
    $response = curl_exec($ch);

    // Check for errors
    if (curl_errno($ch)) {
        $error = curl_error($ch);
        \Log::error("cURL Error: $error");
        curl_close($ch);
        return redirect()->back()->with('error', 'Failed to send message: ' . $error);
    }

    // Close cURL session
    curl_close($ch);

    // Log the API response
    \Log::info("API Response: " . $response);

    // Check if the response indicates success
    if ($response) { // Adjust condition based on API response structure
        return redirect()->back()->with('success', 'Message sent successfully!');
    } else {
        return redirect()->back()->with('error', 'Failed to send message: ' . $response);
    }
}



    
    
    
   
   
   
 
    public function index()
    {
      
            $Organizationshortcodes = Organizationshortcode::All();
            return view('organizationshortcode.index',compact('Organizationshortcodes'));
    }

      
   public function shortcodeindex()
    {
         if(Auth::guard('organization')->check())
        {
             $id = Auth::guard('organization')->user()->organization_id;
               $Id = Auth::user()->api_account;
        }
        else if(Auth::guard('web')->check())
        {
            $id = Auth::guard('web')->user()->organization_id;
              $Id = Auth::user()->api_account;
        //return $id;
        
        } 
     // return $id;
      $wallet = Wallet::where('shopid',$Id)->pluck('amount');
            $Organizationshortcodes = Organizationshortcode::where('organization_id',$id)->get();
            $schedules=Currency_Expenditure::where('shopid','852')->orderBy('currency_expenditure_id', 'desc')->limit(10)->get();
            return view('fcviews.organizationshortcode.shortcode',compact('Organizationshortcodes','schedules','wallet'));
    }

    //get groups
    public function getOrganization()
    {
        if(Auth::guard('organization')->check())
        {
            $id = Auth::guard('organization')->user()->organization_id;
        }
        else if(Auth::guard('web')->check())
        {
            $id = Auth::guard('web')->user()->organization_id;
        }
            $groups = Organization::All();
            return $groups;
    }



    


    //store
    public function storeOrganizationshortcode(Request $request)
    {
        
         if(Auth::guard('organization')->check())
        {
            $id = Auth::guard('organization')->user()->organization_id;
        }
        else if(Auth::guard('web')->check())
        {
            $id = Auth::guard('web')->user()->organization_id;
        //return $id;
        
        }  
        $request->validate([
        
            'group_name' => 'required',
    
                    
                ]);
            

        
        $data = new Organizationshortcode();
        $data->shortcode = $request->name;
        $data->description = $request->description;
        $data->status = 1;
        $data->organization_id = $id;


         //return $data;
        $data->save ();
        //log
        $adminLog = new AuditLog();
        $adminLog->audit_module = "Organization";
        $adminLog->audit_activity = "Organization user ".$request->username ." added by Admin ID# " .$id;
       
        $adminLog->user_category = "Admin";
        $adminLog->user_id = $id;
        ;
        $adminLog->save();
        
        return response()->json($data);
    

}



/**
     * updateGroup the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function updateGroup(Request $request)
    {

      //  try
        { 
            request()->validate([
                'group_name'=> 'required',
                'description' => 'required',
           
            ]);
          //  return $id;
        //current customer details
        $id=$request->group_id;
        $customerdets = Group::where('group_id',$id)->get();
        //updateGroup
        $data = Group::findOrFail($id);
       
        $data->group_name = $request->get('group_name');
        $data->description = $request->get('description');
        $data->status = 1;
        // log data
        $customerLog = new AuditLog();
        $customerLog->audit_module = "Customer";
        $customerLog->audit_activity = "Customer details ";
        
        $customerLog->user_category = "Admin";
        $customerLog->user_id = 1;
        
        $customerLog->save();
        $data->save();

          return redirect()->back()
            ->with('success','Group Edited Succesfully.'); 
            
        }
      //  catch (Exception $exception)
       // {
          //  return back()->withInput()
            //    ->with(['failure' => 'Unexpected error occurred while trying to process your request. Please try Again.']);
      //  }
    }


 //delete
 public function deleteGroup(Request $request,$id)
  {

    //find user details to delete
    $admin = Group::where('group_id',$id)->get();
    //set delete
    $deleteDepartment = Group::find($id);
    $deleteDepartment->delete();
    //set logging
   
    $adminLog = new AuditLog();
    $adminLog->audit_module = "Organization";
    $adminLog->audit_activity = "Organization of details: ".$admin." deleted by Admin ID#" .$id;
    
    $adminLog->user_category = "organization";
    $adminLog->user_id = $id; 
    $adminLog->save();
}
}
