<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;

use App\Mail\ReceiptMail;
use Codedge\Fpdf\Fpdf\Fpdf;
use Barryvdh\DomPDF\Facade\Pdf;
use Carbon\Carbon;

class TransactionController extends Controller
{
    //

    public function index()
    {
        // Fetch data from the URL
        $response = Http::timeout(30)->get('https://transactions.stjohnkenya.org/send_trans.php');

        // Decode JSON response
        $data = $response->json();

        // Pass data to the view
        return view('Payments', ['transactions' => $data]);
    }

    public function checkAndUpdatePayments1()
    {
        // Fetch all records where paystatus is 'pending'
        // $pendingPayments = DB::table('enrollments')->where('paystatus', 'pending')->get();

        $pendingPayments = DB::table('enrollments')
            ->where('paystatus', 'pending')
            ->orderBy('created_at', 'desc')
            ->get();

        foreach ($pendingPayments as $payment) {
            // Make the API call to check if the payment is confirmed
            $response = Http::get('https://transactions.stjohnkenya.org/payment_confirmation.php', [
                'q' => $payment->account // assuming 'account' holds the relevant query value
            ]);

            if ($response->successful()) {
                $data = $response->json();
    
                // Check if payment data was found
                if ($data && isset($data[0]['status']) && $data[0]['status'] == '0') {

                    // Extract the TransAmount from the API response
                    $amount = $data[0]['TransAmount'];
                    $TransId = $data[0]['TransID'];
                    // Update the paystatus to 'paid'
                    DB::table('enrollments')
                        ->where('id', $payment->id)
                        ->update([
                            'paystatus' => 'paid', 
                            'amount' => $amount,
                            'TransID' => $TransId
                        ]);
                        $studentId = $payment->id;
                        $enrollmentData = $this->getEnrollmentData($studentId);
                } else {
                    // Log or handle the case where no payment data was found
                    // You might want to log this for review
                    echo "No payment data found for account number " . $payment->account."<br>";
                    //Log::info("No payment data found for account number " . $payment->account);
                }
            } else {
                // Handle the failed API request, e.g., log the error
                echo "Failed to fetch payment data for account number " . $payment->account;
            }
        }
            // Optional: Return a summary or confirmation that the process is complete
        return response()->json(['message' => 'Payment check and update completed.']);
    }

    public function checkAndUpdatePaymentsold()
    {
        $pendingPayments = DB::table('enrollments')
            ->where('paystatus', 'pending')
            ->orderBy('created_at', 'desc')
            ->get();

        foreach ($pendingPayments as $payment) {
            // Make the API call
            $response = Http::get('https://transactions.stjohnkenya.org/payment_confirmation.php', [
                'q' => $payment->account
            ]);

            if ($response->successful()) {
                $data = $response->json();

                if ($data && isset($data[0]['status']) && $data[0]['status'] == '0') {
                    $transAmount = floatval($data[0]['TransAmount']);
                    $transId = $data[0]['TransID'];

                    // Get course cost from tbl_courses
                    $course = DB::table('tbl_courses')
                        ->where('id', $payment->course)
                        ->first();

                    if ($course) {
                        $courseCost = floatval($course->course_cost);

                        // Decide which amount to save
                        $finalAmount = $transAmount >= $courseCost ? $courseCost : $transAmount;

                        // Update enrollment
                        DB::table('enrollments')
                            ->where('id', $payment->id)
                            ->update([
                                'paystatus' => 'paid',
                                'amount' => $finalAmount,
                                'TransID' => $transId
                            ]);

                        $studentId = $payment->id;
                        $enrollmentData = $this->getEnrollmentData($studentId);
                    } else {
                        echo "Course not found for enrollment ID: {$payment->id}<br>";
                    }
                } else {
                    echo "No payment data found for account number " . $payment->account . "<br>";
                }
            } else {
                echo "Failed to fetch payment data for account number " . $payment->account . "<br>";
            }
        }

        return response()->json(['message' => 'Payment check and update completed.']);
    }

    public function checkAndUpdatePayments()
    {
        // $pendingPayments = DB::table('enrollments')
        //     ->whereIn('paystatus', ['pending', 'partial'])
        //     ->orderBy('created_at', 'desc')
        //     ->get();

            $pendingPayments = DB::table('enrollments')
            ->whereIn('paystatus', ['pending', 'partial'])
            ->where('paymentmode', 'mpesa')
            ->orderBy('created_at', 'desc')
            ->get();

        foreach ($pendingPayments as $payment) {
            // Call API
            $response = Http::get('https://transactions.stjohnkenya.org/payment_confirmation.php', [
                'q' => $payment->account
            ]);

            if ($response->successful()) {
                $transactions = $response->json();

                if ($transactions && is_array($transactions)) {
                    // Get course cost
                    $course = DB::table('tbl_courses')
                        ->where('id', $payment->course)
                        ->first();

                    if (!$course) {
                        echo "Course not found for account: {$payment->account}<br>";
                        continue;
                    }

                    $courseCost = floatval($course->course_cost);

                    // Track new payments
                    foreach ($transactions as $txn) {
                        if (isset($txn['status']) && $txn['status'] == '0') {
                            $transAmount = floatval($txn['TransAmount']);
                            $transId = $txn['TransID'];

                            // Insert only if not already recorded
                            DB::table('partial_payments')->updateOrInsert(
                                ['TransID' => $transId], // unique check
                                [
                                    'account' => $payment->account,
                                    'amount' => $transAmount,
                                    'created_at' => now(),
                                    'updated_at' => now(),
                                ]
                            );
                        }
                    }

                    // After inserting, build all IDs from API for enrollment
                    $apiTransIds = collect($transactions)
                        ->where('status', '0')
                        ->pluck('TransID')
                        ->unique()
                        ->toArray();

                        $allApiTransIds = implode(',', $apiTransIds);

                    // Recalculate total paid so far
                    $totalPaid = DB::table('partial_payments')
                        ->where('account', $payment->account)
                        ->sum('amount');

                    if ($totalPaid >= $courseCost) {
                        // Mark as fully paid
                        DB::table('enrollments')
                            ->where('account', $payment->account)
                            ->update([
                                'paystatus' => 'paid',
                                'amount' => $courseCost,
                                //'TransID' => $transactions[0]['TransID'] ?? null, // save latest
                                'TransID' => $allApiTransIds,
                            ]);

                        // Clear partials
                        DB::table('partial_payments')
                            ->where('account', $payment->account)
                            ->delete();

                        $studentId = $payment->id;
                        $enrollmentData = $this->getEnrollmentData($studentId);
                    } else {
                        // Still partial
                        DB::table('enrollments')
                            ->where('account', $payment->account)
                            ->update([
                                //'paystatus' => 'pending',
                                'amount' => $totalPaid,
                            ]);

                        //$studentId = $payment->id;
                        // $enrollmentData = $this->getEnrollmentData($studentId);
                    }
                } else {
                    echo "No transactions found for account " . $payment->account . "<br>";
                }
            } else {
                echo "Failed to fetch payment data for account " . $payment->account . "<br>";
            }
        }

        return response()->json(['message' => 'Payment check and update completed.']);
    }

    public function postPaymentUpdate(Request $request)
    {
        $request->validate([
            'transactionid' => 'required|string',
            'accountnumber' => 'required|string',
        ]);

        $response = Http::withHeaders([
            'Accept' => 'application/json',
            'Content-Type' => 'application/json',
        ])->post('https://transactions.stjohnkenya.org/update_payment.php', [
            'transactionid' => $request->transactionid,
            'accountnumber' => $request->accountnumber,
        ]);

        $userid=$request->userid;
        //return $userid;

        if ($response->successful()) {

            // Insert into transaction_updates table
            DB::table('transaction_updates')->insert([
                'user_id'          => $request->userid,
                'transaction_id'   => $request->transactionid,
                'account_no'       => $request->accountnumber,
                'transaction_date' => now()->toDateString(),
                'created_at'       => now(),
                'updated_at'       => now(),
            ]);

            return back()->with('success', $response->json()['message'] ?? 'Updated successfully.');
        } else {
            return back()->with('error', 'Failed to update. Server response: ' . $response->body());
        }
    }

    //public function getEnrollmentData()
    public function getEnrollmentData($studentId)
    {
        //$studentId = 6;
        $date=now();
        // Fetch the enrollment record for the specific student
        $enrollment = DB::table('enrollments')
        ->where('id', $studentId)
        ->first();  // Assuming 'id' is the primary key or you could use a different identifier like 'email' or 'student name'
        

        if ($enrollment) {
            $studentnames = $enrollment->name; // Assuming the column name is 'student_name'
            //$date = Carbon::now(); // Current date and time
            $paymentAmount = $enrollment->amount; // Assuming the column name is 'payment_amount'
            $studentmail = $enrollment->email; // Assuming the column name is 'student_email'
            $courseid = $enrollment->course;
            $refno = $enrollment->account;
            $paymentmode = $enrollment->paymentmode;

            // Fetch the course name from the tbl_courses table using the courseid
            $course = DB::table('tbl_courses')
            ->where('id', $courseid)
            ->first();  // Assuming 'id' is the primary key in the tbl_courses table

            if ($course) {
                $service = $course->course_name;  // Assuming the column name is 'course_name'
            } else {
                $service = 'Course not found';
            }

    
        $data=[
           'studentnames' => $studentnames,
           'date' => $date,
           'paymentAmount' => $paymentAmount,
           'service'=> $service,
           'refno'=> $refno, 
           'paymentmode'=> $paymentmode,         
        ];

        //return view('receipt.receipttemplete')->with($data);
        $pdf = Pdf::loadView('receipt.trainingenrollmentreceipt', $data);
 
        //return $pdf->download(); 
        //return $pdf->stream(); 

        Mail::to($studentmail)->cc(['briananikayi@yopmail.com'])->send(new ReceiptMail($pdf,$studentnames));
        return response()->json(['status' => 'success', 'message' => 'Receipt has been sent successfully.']);
        }
    }

    public function reprintReceipt($studentId)
    {
        //$studentId = 6;
        $date=now();
        // Fetch the enrollment record for the specific student
        $enrollment = DB::table('enrollments')
        ->where('id', $studentId)
        ->first();  // Assuming 'id' is the primary key or you could use a different identifier like 'email' or 'student name'
        

        if ($enrollment) {
            $studentnames = $enrollment->name; // Assuming the column name is 'student_name'
            //$date = Carbon::now(); // Current date and time
            $paymentAmount = $enrollment->amount; // Assuming the column name is 'payment_amount'
            $studentmail = $enrollment->email; // Assuming the column name is 'student_email'
            $courseid = $enrollment->course;
            $refno = $enrollment->account;
            $paymentmode = $enrollment->paymentmode;

            // Fetch the course name from the tbl_courses table using the courseid
            $course = DB::table('tbl_courses')
            ->where('id', $courseid)
            ->first();  // Assuming 'id' is the primary key in the tbl_courses table

            if ($course) {
                $service = $course->course_name;  // Assuming the column name is 'course_name'
            } else {
                $service = 'Course not found';
            }

    
        $data=[
           'studentnames' => $studentnames,
           'date' => $date,
           'paymentAmount' => $paymentAmount,
           'service'=> $service,
           'refno'=> $refno,
           'paymentmode'=> $paymentmode,        
        ];

        //return view('receipt.receipttemplete')->with($data);
        $pdf = Pdf::loadView('receipt.trainingenrollmentreceipt', $data);
 
        //return $pdf->download(); 
       // $enrollmentData = $this->getEnrollmentData($studentId);
        return $pdf->stream(); 

        Mail::to($studentmail)->cc(['briananikayi@yopmail.com'])->send(new ReceiptMail($pdf,$studentnames));
        return response()->json(['status' => 'success', 'message' => 'Receipt has been sent successfully.']);
        }
    }

    public function sendReceipt($studentId)
    {
        $enrollment = DB::table('enrollments')
            ->where('id', $studentId)
            ->first();

        if ($enrollment) {
            $studentnames = $enrollment->name;
            $paymentAmount = $enrollment->amount;
            $studentmail = $enrollment->email;
            $courseid = $enrollment->course;
            $refno = $enrollment->account;
            $paymentmode = $enrollment->paymentmode;

            $course = DB::table('tbl_courses')
                ->where('id', $courseid)
                ->first();

            $service = $course ? $course->course_name : 'Course not found';

            $data = [
                'studentnames' => $studentnames,
                'date' => now(),
                'paymentAmount' => $paymentAmount,
                'service' => $service,
                'refno' => $refno,
                'paymentmode' => $paymentmode,
            ];

            $pdf = Pdf::loadView('receipt.trainingenrollmentreceipt', $data);

            Mail::to($studentmail)
                ->cc(['briananikayi@yopmail.com'])
                ->send(new ReceiptMail($pdf, $studentnames));

            return response()->json(['status' => 'success', 'message' => 'Receipt has been sent successfully.']);
        }

        return response()->json(['status' => 'error', 'message' => 'Student not found.']);
    }

}
