<?php

namespace App\Http\Controllers;

use App\Models\TransaksiParkir;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Http;

class VerifyTransController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function skipMember () 
    {
        $transaksi = TransaksiParkir::leftjoin('jenis_mobil as jm','transaksi_parkir.id_kendaraan','=','jm.id')
            ->leftjoin('nama_pos as np_masuk', 'transaksi_parkir.id_pintu_masuk','=','np_masuk.id')
            ->leftjoin('nama_pos as np_keluar', 'transaksi_parkir.veri_kode','=','np_keluar.id')
            ->select('transaksi_parkir.id','transaksi_parkir.no_pol','jm.nama as jenis_mobil','transaksi_parkir.waktu_masuk','transaksi_parkir.status_transaksi',
            'np_masuk.nama as id_pintu_masuk','np_keluar.nama as veri_kode',
            'transaksi_parkir.veri_date as waktu_keluar','transaksi_parkir.veri_check')
            /* --- Production -----*/
            ->where('transaksi_parkir.veri_check','1')
            // ->whereNotNull('transaksi_parkir.veri_check')
            ->orderbydesc('transaksi_parkir.veri_date')
            /* --- debuging -----*/
            // ->where('transaksi_parkir.status','0')
            // ->where('transaksi_parkir.id_kendaraan', 'Mobil')
            // ->where('transaksi_parkir.id_pintu_masuk', '01')
            // ->orderbydesc('transaksi_parkir.waktu_masuk')
            /* ------------------*/
            ->limit(3)
            ->get();

            Log::info(json_encode($transaksi));
            
            if ($transaksi->status_transaksi && $transaksi->status_transaksi == 3) {
                $dateNow = Carbon::now();

                DB::table('transaksi_parkir')
                ->where('no_pol', $transaksi->no_pol )
                ->update(['veri_check' => 2,
                'veri_date' => $dateNow,
                'veri_adm' => 'SYSTEM'
                ]);
                
                // $response = true;
                // $message = [
                //     'no_pol' => $RealtimeTrans->no_pol,
                //     'message' => 'member skipped'
                // ];
            }

        return $transaksi;
    }
    
    public function index(Request $request)
    {
        if ($request->ajax()) {

            $transaksi = TransaksiParkir::leftjoin('jenis_mobil as jm','transaksi_parkir.id_kendaraan','=','jm.id')
            ->leftjoin('nama_pos as np_masuk', 'transaksi_parkir.id_pintu_masuk','=','np_masuk.id')
            ->leftjoin('nama_pos as np_keluar', 'transaksi_parkir.id_pintu_keluar','=','np_keluar.id')
            ->select('transaksi_parkir.id','transaksi_parkir.no_pol','jm.nama','transaksi_parkir.waktu_masuk',
            'transaksi_parkir.veri_date as waktu_keluar',
            // 'transaksi_parkir.id_pintu_masuk','transaksi_parkir.id_pintu_keluar',
            'np_masuk.nama as id_pintu_masuk','np_keluar.nama as id_pintu_keluar',
            'transaksi_parkir.veri_check','transaksi_parkir.veri_kode','transaksi_parkir.status_transaksi')
            /* --- Production -----*/
            ->where('transaksi_parkir.veri_check','1')
            // ->whereNotNull('transaksi_parkir.veri_check')
            ->orderbydesc('transaksi_parkir.veri_date')
            /* --- debuging -----*/
            // ->where('transaksi_parkir.status','0')
            // ->where('transaksi_parkir.id_kendaraan', 'Mobil')
            // ->where('transaksi_parkir.id_pintu_masuk', '01')
            // ->orderbydesc('transaksi_parkir.waktu_masuk')
            /* ------------------*/
            ->limit(3)
            ->get();

            // Log::info($transaksi);

            // $data = [];
            foreach ($transaksi as $data) {
                if ($data->status_transaksi && $data->status_transaksi == '3') {
                    $dateNow = Carbon::now();
    
                    $query = DB::table('transaksi_parkir')
                    ->where('no_pol', $data->no_pol )
                    ->where('status', 1)
                    ->update(['veri_check' => 2,
                    'veri_date' => $dateNow,
                    'veri_adm' => 'SYSTEM'
                    ]);
                    
                    Log::info('Member update ' . $query);

                    // $response = true;
                    // $message = [
                    //     'no_pol' => $RealtimeTrans->no_pol,
                    //     'message' => 'member skipped'
                    // ];
                }
                // $transaksi = $data;
                Log::info($transaksi);
            }

            $data = $transaksi;

            // Log::info($transaksi);

            $table = DataTables::of($data)

            ->addIndexColumn()

            ->addColumn('id', function($row){
                return $row->id;
            })

            ->addColumn('no_pol', function($row){
                return $row->no_pol ?? '';
            })

            ->addColumn('jenis_mobil', function($row){
                return $row->jenis_mobil ?? '';
            })

            ->addColumn('waktu_masuk', function($row){
                return $row->waktu_masuk ?? '';
            })

            ->addColumn('waktu_keluar', function($row){
                return $row->waktu_keluar ?? '';
            })

            ->addColumn('id_pintu_masuk', function($row){
                // return $row->id_pintu_masuk ?? '';
                return '<span class="badge badge-pill badge-secondary">'.$row->id_pintu_masuk.'</span>' ?? '';
            })

            ->addColumn('out_gate', function($row){
                // return $row->veri_kode ?? '';
                return '<span class="badge badge-pill badge-success">'.$row->veri_kode.'</span>' ?? '';
            })

            ->addColumn('status', function($row){
                return $row->veri_check ?? '';
            })

            ->rawColumns(['id_pintu_masuk','out_gate']);

            return $table->make(true);
        }

        return view('verify');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */

    // private function getCurlImage ($url)
    // {
    //     $ch = curl_init();
    //     curl_setopt($ch, CURLOPT_URL, $url);
    //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    //     $result = curl_exec($ch);

    //     if (curl_errno($ch)) {
    //         Log::error('cURL error: ' . curl_error($ch));
    //         $result = false;
    //     }

    //     curl_close($ch);

    //     return $result;
    //     Log::info($result);
    // }

    // private function getCurlImage($url)
    // {
    //     // Decode URL to ensure it's correctly formatted
    //     $url = htmlspecialchars_decode($url);
    //     $parsedUrl = parse_url($url);

    //     // Mengambil bagian 'user' dan 'pass' dari URL
    //     $user = $parsedUrl['user'] ?? null;
    //     $pass = $parsedUrl['pass'] ?? null;

    //     $ch = curl_init();
    //     curl_setopt($ch, CURLOPT_URL, $url);
    //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //     curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
    //     curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $pass); // Username dan password
    //     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    //     curl_setopt($ch, CURLOPT_HTTPHEADER, [
    //         'Content-Type: image/jpeg',  // Ubah sesuai tipe konten yang diharapkan
    //         'Accept: image/jpeg'
    //         // 'WWW-Authenticate: Digest'
    //     ]);

    //     $result = curl_exec($ch);

    //     if (curl_errno($ch)) {
    //         Log::error('cURL error: ' . curl_error($ch));
    //         $result = false;
    //     } else {
    //         $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    //         if ($http_code != 200) {
    //             Log::error('HTTP error: ' . $http_code);
    //             $result = false;
    //         }
    //     }

    //     curl_close($ch);

    //     // Log response headers
    //     Log::info('cURL response headers: ' . json_encode(curl_getinfo($ch)));

    //     // Optional: Log the response if it's not an image
    //     if ($result !== false && @imagecreatefromstring($result) === false) {
    //         Log::error('Invalid image data received');
    //         $result = false;
    //     }

    //     return $result;
    // }

    private function getCurlImage($url)
    {
        // Decode URL to ensure it's correctly formatted
        $url = htmlspecialchars_decode($url);
        $parsedUrl = parse_url($url);

        // Mengambil bagian 'user' dan 'pass' dari URL
        $user = $parsedUrl['user'] ?? null;
        $pass = $parsedUrl['pass'] ?? null;
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
        curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $pass); // Username dan password
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: image/jpeg',  // Ubah sesuai tipe konten yang diharapkan
            'Accept: image/jpeg'
        ]);

        $result = curl_exec($ch);

        if (curl_errno($ch)) {
            Log::error('cURL error: ' . curl_error($ch));
            $result = false;
        } else {
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if ($http_code != 200) {
                Log::error('HTTP error: ' . $http_code);
                $result = false;
            }
        }

        curl_close($ch);

        // Log response headers
        Log::info('cURL response headers: ' . json_encode(curl_getinfo($ch)));

        // Optional: Log the response if it's not an image
        // if ($result !== false) {
        //     // Check if the result is a valid image
        //     if (@imagecreatefromstring($result) === false) {
        //         Log::error('Invalid image data received');
        //         $result = false;
        //     } else {
                // Convert the image data to base64
                $result = base64_encode($result);

        //         $path = storage_path('app/public');  // Path direktori
        //         $imagePath = $path . '/image.jpeg';

        //         // Buat direktori jika belum ada
        //         if (!file_exists($path)) {
        //             mkdir($path, 0755, true);  // Buat direktori dengan izin 0755, dan buat sub-direktori jika diperlukan
        //         }
        //         // Optionally, save the image to a file for testing
        //         // file_put_contents('storage/app/public/image.jpeg', $result);  // Adjust path and filename
        //         file_put_contents($imagePath, $result);
        //     }
        // }

        return $result;
    }

    public function showImages(Request $request)
    {
        try {
            $transaksi = TransaksiParkir::where('id', $request->id)
                ->select('id','no_pol','pic_body_masuk','pic_body_keluar','pic_driver_masuk',
                'pic_driver_keluar','pic_no_pol_masuk','pic_no_pol_keluar','veri_kode')
                ->where('no_pol', $request->no_pol)
                ->firstOrFail();

            Log::info(json_encode($transaksi));

            $getCamera = DB::table('config_pos_hardware')
            ->select('video1_conn as body_cam','video2_conn as drive_cam')
            ->where('id_pos', $transaksi->veri_kode)
            ->first();
            
            Log::info(json_encode($getCamera));
            // Log::info($getCamera);
            /* Body Masuk */
            if (!empty($transaksi->pic_body_masuk) && is_resource($transaksi->pic_body_masuk)) {
                $transaksi->pic_body_masuk = base64_encode(stream_get_contents($transaksi->pic_body_masuk)) ?? 'Tidak ada FOTO';
            } else {
                $transaksi->pic_body_masuk = 'Tidak ada foto';
            }

            $baseIn = 
            Log::info(json_encode('foto masuk' .$transaksi->pic_body_masuk));
            
            /* Driver Masuk */
            if (!empty($transaksi->pic_driver_masuk) && is_resource($transaksi->pic_driver_masuk)) {
                $transaksi->pic_driver_masuk = base64_encode(stream_get_contents($transaksi->pic_driver_masuk)) ?? 'Tidak ada FOTO';
            } else {
                $transaksi->pic_driver_masuk = 'Tidak ada foto';
            }
            Log::info(json_encode($transaksi->pic_driver_masuk));

            $ImgBodyOut = $this->getCurlImage($getCamera->body_cam);
            $ImgDriveOut = $this->getCurlImage($getCamera->drive_cam);
            // Log::info([$ImgBodyOut]);
            // Log untuk memastikan URL benar
            // Log::info('Body Cam URL: ' . $getCamera->body_cam);
            // Log::info('Drive Cam URL: ' . $getCamera->drive_cam);

            // $ImgBodyOut = $this->getCurlImage($getCamera->body_cam);
            // // try { 
            //     $ImgBodyOut = Http::accept('image/jpeg')
            //     ->withOptions(['verify' => false,])
            //     ->withHeaders(['Authorization' => 'Digest username="admin", realm="your_realm", nonce="nonce_value", response="response_hash"'])
            //     ->get('http://192.168.200.64/ISAPI/streaming/channels/1/picture');

                // if ($ImgBodyOut->successful()) {
                    // Konversi gambar ke base64
                    // $ImgBodyOut = base64_encode($ImgBodyOut->body()); 
            //     } else {
            //         Log::error('Failed to get image. Status code: ' . $ImgBodyOut->status());
            //         return 'Tidak ada foto';
            //     }

            // } catch (\Exception $e) {
            //     return response()->json([
            //         'message' => 'Gagal mengambil gambar',
            //         'error' => $e->getMessage(),
            //     ], 500);
            // }
            
                // ])->get($getCamera->body_cam);
            // ])->get('http://192.168.200.64/ISAPI/streaming/channels/1/picture&auth=digest&username=admin&password=rootjuga1');
            // $ImgDriveOut = $this->getCurlImage($getCamera->drive_cam);

            // Log hasil cURL
            Log::info('ImgBodyOut: ' . ($ImgBodyOut ? 'Image received' : 'Failed to get image'));
            // Log::info('ImgDriveOut: ' . ($ImgDriveOut ? 'Image received' : 'Failed to get image'));
            // dd($transaksi);
            return response()->json([
                'pic_masuk' => $transaksi->pic_body_masuk,
                'driver_masuk' => $transaksi->pic_driver_masuk,
                'pic_keluar' => $ImgBodyOut,
                'driver_keluar' => $ImgDriveOut,
            ]);
        } catch (\Exception $e) {
            Log::error('Error fetching data: ' . $e->getMessage());
            return response()->json(['error' => 'Data not found or other error'], 500);
        }
    }        
        // $transaksi = TransaksiParkir::where('id', $request->id)->where('no_pol', $request->no_pol)->firstOrfail();

        // // $pic_masuk = $transaksi->pic_body_masuk ? base64_encode(stream_get_contents($transaksi->pic_body_masuk)) : null;
        // $transaksi->pic_body_masuk = base64_encode(stream_get_contents($transaksi->pic_body_masuk));
        // // } catch (\Exception $e) {
        // //     return response()->json([
        // //         'message' => 'Gagal mengambil gambar',
        // //         'error' => $e->getMessage(),
        // //     ], 500);
        // // }

        // return response()->json([
        //     'transaksi' => $transaksi,
        //     // 'pic_masuk' => $pic_masuk,
        // //     // 'pic_keluar' => $pic_keluar,
        // ]);


    // public function show($no_pol)
    // {
    //     $transaksi = TransaksiParkir::where('no_pol', $no_pol)->orderBy('waktu_masuk','desc')->first();
        
    //     // if($transaksi->veri_kode) {
    //     //     $paramsBodyKeluar = DB::table('config_pos_hardware')->select('video1_conn')->where('id_pos', $transaksi->veri_kode)->first();
    //     // }
    //     dd($no_pol,json_encode($transaksi));
    //     try {
    //         $pic_masuk = $transaksi->pic_body_masuk ? base64_encode(stream_get_contents($transaksi->pic_body_masuk)) : null;
    //     } catch (\Exception $e) {
    //         return response()->json([
    //             'message' => 'Gagal mengambil gambar',
    //             'error' => $e->getMessage(),
    //         ], 500);
    //     }
        // if($paramsBodyKeluar) {
        //     // $pic_keluar = file_get_contents ($paramsBodyKeluar->video1_conn);
        //     $pic_keluar = $this->getCurlImage($paramsBodyKeluar->video1_conn);
        // } else {

        // }

        // $pic_masuk = '';
        // if ($transaksi->pic_body_masuk) {
        //     try {
        //         $pic_masuk = base64_encode(stream_get_contents($transaksi->pic_body_masuk));
        //     } catch (\Exception $e) {
        //         // Tangani kesalahan saat mengambil gambar
        //         Log::error('Gagal mengambil gambar masuk: ' . $e->getMessage());
        //     }
        // }

        // $pic_keluar = null;
        // // Mengambil gambar keluar dari koneksi video1_conn jika ada
        // if ($paramsBodyKeluar && $paramsBodyKeluar->video1_conn) {
        //     try {

        //         $pic_keluar = $this->getCurlImage($paramsBodyKeluar->video1_conn);
        //         // $pic_keluar_content = file_get_contents($paramsBodyKeluar->video1_conn);
        //         // if ($pic_keluar_content !== false) {
        //         //     $pic_keluar = base64_encode($pic_keluar_content);
        //         // }
        //     } catch (\Exception $e) {
        //         // Tangani kesalahan saat mengambil gambar
        //         $pic_keluar = null;
        //         Log::error('Gagal mengambil gambar keluar: ' . $e->getMessage());
        //     }
        // }

        // dd($transaksi);

        // $pic_masuk = base64_encode(stream_get_contents($transaksi->pic_body_masuk));
    //     dd($transaksi,$pic_masuk);
    //     // $pic_keluar = base64_encode(stream_get_contents($transaksi->pic_body_keluar));

    //     // $pic_keluar = $transaksi->pic_body_keluar ? base64_encode(stream_get_contents($transaksi->pic_body_keluar)) : null;

    //     // Mengembalikan gambar dalam format JSON
    //     return response()->json([
    //         'pic_masuk' => $pic_masuk,
    //         // 'pic_keluar' => $pic_keluar,
    //     ]);
    //     // return view('verify', [
    //     //     'transaksi' => $transaksi,
    //     //     'pic_masuk' => $pic_masuk,
    //     //     'pic_keluar' => $pic_keluar,
    //     // ]);
    //     // return response()->json($transaksi);
    // }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        try {
            Log::info([$id, $request->no_pol]);
            $no_pol = $request->input('no_pol');
            $user = Auth::user()->nomer;
            $dateNow = Carbon::now();
            $data = TransaksiParkir::where('id',$id)->where('no_pol',$no_pol)->orderBy('waktu_masuk','desc')->first(); // Ganti YourModel dengan nama model Anda
            // $data->veri_check = 2;
            $data->veri_check = $request->input('veri_check');
            $data->veri_adm = $user;
            $data->veri_time = $dateNow;
            $data->save();

            return response()->json([
                'message' => 'Data berhasil diperbarui',
            ]);
        } catch (Exception $e) {
            return response()->json([
                'message' => 'Gagal melakukan update',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
