<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Traits\SendsNotifications;
use Carbon\Carbon;

class StudentsRegisterController extends Controller
{
    use SendsNotifications;
    //

    public function StudentSelfRegister()
    {
        $contributions="";
       // $stations = DB::table('tbl_training_stations')->get();
        $stations = DB::table('tbl_training_stations')
            ->where('status', 'active')
            ->get();
        $courses = DB::table('tbl_courses')->get();

        //return $courses;

        $data=[
            'contributions' => $contributions,
            'stations' => $stations,
            'courses' => $courses, 

        ];

        return view('studentSelfRegister')->with($data);
    }

    public function SelfEnrolmentTab(Request $request) {
        // Validate the form data
        $validatedData = $request->validate([
            'idno' => 'required|string|max:255',
            'account' => 'required|string|max:10',
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:255',
            //'mpesaphone' => 'required|string|max:255',
            'email' => 'nullable|email',
            'course' => 'required',
            'station' => 'required',
            'startdate' => 'required|date',
            'paymentmode' => 'required',
        ]);

         // Check the input and apply the logic
        $company = $request->input('companyname');
        $finalCompany = empty(trim($company)) ? 'Self' : $company;


        // Construct the full account value
        $account = "TRN" . $request->account;

        // Check if the account already exists
        $exists = DB::table('enrollments')->where('account', $account)->exists();

        if ($exists) {
            return redirect()->back()->with('error', 'Multiple applications are not allowed.[');
        }

        // ✅ Check if the same idno + course exists in the last 6 months
        $existsWithin6Months = DB::table('enrollments')
            ->where('idno', $request->idno)
            ->where('course', $request->course)
            ->where('created_at', '>=', Carbon::now()->subMonths(6))
            ->exists();

        if ($existsWithin6Months) {
            return redirect()->back()->with('error', 'Another registration for this course already exists for this trainee within the last 6 months.');
        }

         // Save the enrollment data to the database using DB facade
        $enrollmentId = DB::table('enrollments')->insertGetId([
        'idno' => $request->idno,
        'account' => "TRN".$request->account,
        'name' => strtoupper($request->name),
        'phone' => $request->phone,
        'email' => $request->email,
        'course' => $request->course,
        'station' => $request->station,
        'startdate' => $request->startdate,
        'paymentmode' => $request->paymentmode,
        'companyname' => strtoupper($finalCompany),
        'created_at' => now(),
        'updated_at' => now()
            ]);

            $courseDetails = DB::table('tbl_courses')->where('id', $request->course)->first();
            $courseCost = $courseDetails->course_cost; // Store the cost in a variable

     // Check if the student with the given idno exists in tbl_students_data
     $student = DB::table('tbl_students_data')->where('national_id', $request->idno)->first();

     // If the student with the given idno doesn't exist, insert into tbl_students_data
     if (!$student) {
         // Insert data into tbl_students_data
         DB::table('tbl_students_data')->insert([
             'national_id' => $request->idno,
             'full_names' => $request->name,
             'phone' => $request->phone,
             'gender' => $request->gender,
             'email' => $request->email,
             'registration_date' => now(),
             'registered_by' => "Self Online"
         ]);
     }


     // Check if the payment mode is 'mpesa' and execute a function
    if ($request->paymentmode === 'mpesa') {
        //$this->executeMpesaFunction($request); // Call your function
        $phone = $request->mpesaphone; // Example phone number
        //$Amount = '1'; // Example amount
        $Amount = $courseCost; // Example amount
        $accountno ="TRN".$request->account; 

        $this->payment($phone, $Amount, $accountno);
        return redirect()->back()->with('success', 'Enrolment submitted successfully. Enter your pin to complete payment');

    }
    
        // Redirect the user or return a response
        return redirect()->back()->with('success', 'Enrolment submitted successfully');
    }

    public function EnrolledStudentstable()
    {
        $contributions="";
        $students = DB::table('enrollments')->get();
        $courses = DB::table('tbl_courses')->get();
        $stations = DB::table('tbl_training_stations')->get();

        $students = DB::table('enrollments')
            ->join('tbl_courses', 'enrollments.course', '=', 'tbl_courses.id')
            ->select('enrollments.*', 'tbl_courses.course_name')
            ->get();

            $students = DB::table('enrollments')
            ->join('tbl_courses', 'enrollments.course', '=', 'tbl_courses.id')
            ->select('enrollments.*', 'tbl_courses.course_name')
            ->orderBy('enrollments.id', 'desc') // Ordering by most recent
            ->get();

            $students = DB::table('enrollments')
            ->join('tbl_courses', 'enrollments.course', '=', 'tbl_courses.id')
            ->select('enrollments.*', 'tbl_courses.course_name')
            ->orderBy('enrollments.created_at', 'desc') // Most recent by creation time
            ->get();



            $admissions = DB::table('tbl_admissions')
            ->join('enrollments', 'tbl_admissions.student_id', '=', 'enrollments.id')
            ->join('tbl_courses', 'tbl_admissions.course_id', '=', 'tbl_courses.id')
            ->select(
                'tbl_admissions.*',
                'enrollments.name as student_name',
                'enrollments.idno',
                'enrollments.station',
                'enrollments.phone',
                'enrollments.email',
                'tbl_courses.course_name'
            )
            ->get();
    
            // Get a list of admitted students
            $admittedStudentIds = $admissions->pluck('student_id')->unique()->toArray();


        //return $admittedStudentIds;
        
        $data=[
            'contributions' => $contributions,
            'students' => $students, 
            'courses' => $courses, 
            'stations' => $stations,
            'admittedStudentIds' => $admittedStudentIds,
        ];

        return view('training.studentenrolmenttable')->with($data);
    }

    public function WeeklyEnrolledStudentstable()
    {
        $contributions="";
        $students = DB::table('enrollments')->get();
        $courses = DB::table('tbl_courses')->get();
        $stations = DB::table('tbl_training_stations')->get();

        $startOfWeek = Carbon::now()->setTimezone('Africa/Nairobi')->startOfWeek();
        $endOfWeek = Carbon::now()->setTimezone('Africa/Nairobi')->endOfWeek();
        $startOfWeek = $startOfWeek->toDateTimeString();
        $endOfWeek = $endOfWeek->toDateTimeString();;

        $students = DB::table('enrollments')
            ->join('tbl_courses', 'enrollments.course', '=', 'tbl_courses.id')
            ->select('enrollments.*', 'tbl_courses.course_name')
            ->get();

            $students = DB::table('enrollments')
            ->join('tbl_courses', 'enrollments.course', '=', 'tbl_courses.id')
            ->select('enrollments.*', 'tbl_courses.course_name')
            ->orderBy('enrollments.id', 'desc') // Ordering by most recent
            ->get();

            $students = DB::table('enrollments')
            ->join('tbl_courses', 'enrollments.course', '=', 'tbl_courses.id')
            ->select('enrollments.*', 'tbl_courses.course_name')
            ->orderBy('enrollments.created_at', 'desc') // Most recent by creation time
            ->get();

            $students = DB::table('enrollments')
            ->join('tbl_courses', 'enrollments.course', '=', 'tbl_courses.id')
            ->select('enrollments.*', 'tbl_courses.course_name')
            ->whereBetween('enrollments.created_at', [$startOfWeek, $endOfWeek])
            ->orderBy('enrollments.created_at', 'desc')
            ->get();

            $admissions = DB::table('tbl_admissions')
            ->join('enrollments', 'tbl_admissions.student_id', '=', 'enrollments.id')
            ->join('tbl_courses', 'tbl_admissions.course_id', '=', 'tbl_courses.id')
            ->select(
                'tbl_admissions.*',
                'enrollments.name as student_name',
                'enrollments.idno',
                'enrollments.station',
                'enrollments.phone',
                'enrollments.email',
                'tbl_courses.course_name'
            )
            ->get();
    
            // Get a list of admitted students
            $admittedStudentIds = $admissions->pluck('student_id')->unique()->toArray();


        //return $admittedStudentIds;
        
        $data=[
            'contributions' => $contributions,
            'students' => $students, 
            'courses' => $courses, 
            'stations' => $stations,
            'admittedStudentIds' => $admittedStudentIds,
        ];

        return view('training.weeklystudentenrolmenttable')->with($data);
    }

    public function MonthlyEnrolledStudentstable()
    {
        $contributions="";
        $students = DB::table('enrollments')->get();
        $courses = DB::table('tbl_courses')->get();
        $stations = DB::table('tbl_training_stations')->get();

       // Define start and end of current month
       $startOfMonth = Carbon::now()->setTimezone('Africa/Nairobi')->startOfMonth()->toDateTimeString();
       $endOfMonth = Carbon::now()->setTimezone('Africa/Nairobi')->endOfMonth()->toDateTimeString();

       // Get students enrolled this month
       $students = DB::table('enrollments')
                ->join('tbl_courses', 'enrollments.course', '=', 'tbl_courses.id')
                ->select('enrollments.*', 'tbl_courses.course_name')
                ->whereBetween('enrollments.created_at', [$startOfMonth, $endOfMonth])
                ->orderBy('enrollments.created_at', 'desc')
                ->get();

           $admissions = DB::table('tbl_admissions')
            ->join('enrollments', 'tbl_admissions.student_id', '=', 'enrollments.id')
            ->join('tbl_courses', 'tbl_admissions.course_id', '=', 'tbl_courses.id')
            ->select(
                'tbl_admissions.*',
                'enrollments.name as student_name',
                'enrollments.idno',
                'enrollments.station',
                'enrollments.phone',
                'enrollments.email',
                'tbl_courses.course_name'
            )
            ->get();
    
            // Get a list of admitted students
            $admittedStudentIds = $admissions->pluck('student_id')->unique()->toArray();

        //return $admittedStudentIds;
        $currentMonth = Carbon::now()->setTimezone('Africa/Nairobi')->format('F Y');
        
        $data=[
            'contributions' => $contributions,
            'currentMonth' => $currentMonth,
            'students' => $students, 
            'courses' => $courses, 
            'stations' => $stations,
            'admittedStudentIds' => $admittedStudentIds,
        ];

        return view('training.monthlystudentenrolmenttable')->with($data);
    }


    public function anotherFunction() {
        // Assuming you have the required data here
        $phone = '0702230627'; // Example phone number
        $Amount = '10'; // Example amount
        $accountno = 'ABC121113'; // Example account number
    
        // Call the payment function and pass the required parameters
        $this->payment($phone, $Amount, $accountno);
    }

    // StudentController.php
    public function settleBill($id)
    {
        // Retrieve student information using the DB facade
        $student = DB::table('enrollments')->where('id', $id)->first();

        //return  $student;

        if ($student) {
            // Assuming you have an 'amount' field and you need to update 'paystatus'
            // Also assume there's a column 'amount' in the students table for this example
            $Amount = $student->amount;
            $phone = $student->phone;
            $accountno = $student->account;


            $courseDetails = DB::table('tbl_courses')->where('id', $student->course)->first();
            $Amount = $courseDetails->course_cost; // Store the cost in a variable

            //$Amount="1";

            $this->payment($phone, $Amount, $accountno);
            // Perform additional logic here if needed (e.g., processing the amount)

            // Update the student's paystatus
           // DB::table('enrollments')->where('id', $id)->update(['paystatus' => 'paid']);

            return redirect()->back()->with('success', 'Promt submitted successfully. Enter your pin to complete payment');

            return response()->json([
                'success' => 'Bill settled successfully!',
                'amount' => $amount,
                'phoneNumber' => $phoneNumber
            ]);
        }

        return redirect()->back()->with('error', 'Student not found!');
        
    }

    public function confirmManualPayment($id)
    {
      // Step 1: Get the student record from enrollments
            $student = DB::table('enrollments')->where('id', $id)->first();


            if ($student && $student->paystatus !== 'paid') {
                // Step 2: Get course details using course ID from student record
                $course = DB::table('tbl_courses')->where('id', $student->course)->first();

                
                // Step 3: Determine amount
                $amount = $course ? $course->course_cost : 0;

               // return $amount;

                // Step 4: Generate a random transaction ID (e.g., prefixed + random string)
                $transactionId = 'MANUAL-' . strtoupper(Str::random(10));

                // Step 5: Update enrollments table
                DB::table('enrollments')
                    ->where('id', $id)
                    ->update([
                        'paystatus' => 'paid',
                        'amount' => $amount,
                        'TransID' => $transactionId,
                        'updated_at' => now()
                    ]);

                return redirect()->back()->with('success', 'Manual payment confirmed for account: ' . $student->account);
            }

            return redirect()->back()->with('error', 'Unable to confirm payment.');
    }


    

    public function payment($phone, $Amount, $accountno)
    {
       
          $TransactionDesc="Training Enrolment";
          $AccountReference=$accountno;
          //$Amount=$_POST['amount'];
          
          $length=strlen($phone);
            if ($length==10)
                {
                $tel= substr($phone, 1);
                    $code="254";
                    $PartyA = $code.$tel;
                //echo $to;
                }
            elseif($length<=8)
                {
                $to=$phone;
                echo "invalid phone";
                //echo $to;
                }
            elseif($length >=11)
                {
                $PartyA=$phone;
                //echo $to;
                } 
        
      
        # access token
        $consumerKey = 'zwIdqxhxNhXyMC3FzzZFAKZHXZ1xuHmWC6iKOcDaVCIIw34z'; //Fill with your app Consumer Key
        $consumerSecret = 'gFpN6CAGeNngqXlDSTGcy6oGD68PgEjSA67WAIYUnEzTWOi6APu3es5hvr31kjXf'; // Fill with your app Secret
      
        # define the variales
        # provide the following details, this part is found on your test credentials on the developer account
        $BusinessShortCode = '224444';
        //$BusinessShortCode = '580900';
        $Passkey = 'd7744a046891518fcd6f72f75931938aaa389fb757b886dbd9d826efd30d3f7b';  
        
        /*
          This are your info, for
          $PartyA should be the ACTUAL clients phone number or your phone number, format 2547********
          $AccountRefference, it maybe invoice number, account number etc on production systems, but for test just put anything
          TransactionDesc can be anything, probably a better description of or the transaction
          $Amount this is the total invoiced amount, Any amount here will be 
          actually deducted from a clients side/your test phone number once the PIN has been entered to authorize the transaction. 
          for developer/test accounts, this money will be reversed automatically by midnight.
        */
        
        // $PartyA = '254704170146'; // This is your phone number, 
        //$AccountReference = 'GURUSNATION';
        //$TransactionDesc = 'STAY SAFE DURING COVID';
        //$Amount = '1';
       
        # Get the timestamp, format YYYYmmddhms -> 20181004151020
        $Timestamp = date('YmdHis');    
        
        # Get the base64 encoded string -> $password. The passkey is the M-PESA Public Key
        $Password = base64_encode($BusinessShortCode.$Passkey.$Timestamp);
      
        # header for access token
        $headers = ['Content-Type:application/json; charset=utf8'];
      
          # M-PESA endpoint urls
       // $access_token_url = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
       // $initiate_url = 'https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest';
        
         $access_token_url = 'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
        $initiate_url = 'https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest';
      
        # callback url
        $CallBackURL = 'https://briananikayi.com/mpesa/call_back.php';  
      
        $curl = curl_init($access_token_url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_HEADER, FALSE);
        curl_setopt($curl, CURLOPT_USERPWD, $consumerKey.':'.$consumerSecret);
        $result = curl_exec($curl);
        $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $result = json_decode($result);
        $access_token = $result->access_token;  
        curl_close($curl);
      
        # header for stk push
        $stkheader = ['Content-Type:application/json','Authorization:Bearer '.$access_token];
      
        # initiating the transaction
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $initiate_url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $stkheader); //setting custom header
      
        $curl_post_data = array(
          //Fill in the request parameters with valid values
          'BusinessShortCode' => $BusinessShortCode,
          'Password' => $Password,
          'Timestamp' => $Timestamp,
          'TransactionType' => 'CustomerPayBillOnline',
          'Amount' => $Amount,
          'PartyA' => $PartyA,
          'PartyB' => $BusinessShortCode,
          'PhoneNumber' => $PartyA,
          'CallBackURL' => $CallBackURL,
          'AccountReference' => $AccountReference,
          'TransactionDesc' => $TransactionDesc
        );
      
        $data_string = json_encode($curl_post_data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
        $curl_response = curl_exec($curl);
        //print_r($curl_response);
      
    }

    public function editenrolment($id)
    {
        // Fetch the student record from the database
        $student = DB::table('enrollments')->where('id', $id)->first();

       // return $student;

        if (!$student) {
            return redirect()->back()->with('error', 'Student not found.');
        }

            // Fetch all courses from tbl_courses
        $courses = DB::table('tbl_courses')->get();

         // Fetch all stations
        //$stations = DB::table('tbl_training_stations')->get();
         $stations = DB::table('tbl_training_stations')
        ->select('id', 'station_name')
        ->where('status', '=', 'active')
        ->where('station_name', '!=', $student->station)
        ->orderBy('station_name')
        ->get();

        //return $stations;
        
        // Pass both the student and courses to the view
        return view('training.studentsenrolmentedit', compact('student', 'courses','stations'));

        // Pass data to the edit view
       // return view('training.studentsenrolmentedit', compact('student'));
    }

    public function updateenrolment(Request $request, $id)
    {
        // Validate the input data
        $request->validate([
            'name' => 'required|string|max:255',
            'idno' => 'required|string|max:50',
            'phone' => 'required|string|max:15',
            'email' => 'nullable|email',
            'station' => 'required|string|max:100',
            'paymentmode' => 'nullable|string|max:50',
            'coursecode' => 'required|integer', // course ID from tbl_courses
        ]);

        // Get the selected coursecode from tbl_courses
        $course = DB::table('tbl_courses')
            ->where('id', $request->coursecode)
            ->first();

        if (!$course) {
            return redirect()->back()->with('error', 'Invalid course selected.');
        }

        DB::beginTransaction();

        try {
            // 1️⃣ Update the enrollment record
            DB::table('enrollments')
                ->where('id', $id)
                ->update([
                    'name' => $request->name,
                    'idno' => $request->idno,
                    'phone' => $request->phone,
                    'email' => $request->email,
                    'station' => $request->station,
                    'paymentmode' => $request->paymentmode,
                    'course' => $request->coursecode, // store actual course ID
                    'updated_at' => now(),
                ]);

            // 2️⃣ Update the certified_members record if exists
            DB::table('certified_members')
                ->where('admid', $id)
                ->update([
                    'phone' => $request->phone,
                    'email' => $request->email,
                    'training_location' => $request->station,
                    //'updated_at' => now(),
                ]);

            DB::commit();

            return redirect()->route('weeklyStudentenrolments')->with('success', 'Student enrollment and certification details updated successfully.');

        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->back()->with('error', 'Update failed: ' . $e->getMessage());
        }
    }

}
