<?php

namespace App\Http\Controllers\Report;

use Yajra\DataTables\Facades\DataTables;
use App\Http\Controllers\Controller;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\Library\Booklist;
use App\Models\Library\Bookmember;
use App\Models\Library\Bookissue;
use App\Exports\LibraryExport;
use Illuminate\Http\Request;
use App\Models\User;
use PDF;

class LibraryReportController extends Controller{
    public function index(){
        return view('report.Library.index');
    }

    // book return report
    public function bookReturnReport(Request $request){
        $user_type = '';
        $date = '';
        $user_types = User::select('user_type')->distinct()->get();
        return view('report.Library.book-return-report',compact('user_types'));
    }
    public function bookReturnReportSearch(Request $request){
        try {
            // Parse the date range
            $daterange = $request->date;
            $from = substr($daterange, 0, -13);
            $from = date("Y-m-d", strtotime($from));
            $to = substr($daterange, -10);
            $to = date("Y-m-d", strtotime($to));
            // Fetch the selected columns or set defaults
            $selectedColumns = $request->input('selected_columns', []);
            if (empty($selectedColumns)) {
                $selectedColumns = ['issue_date', 'estimate_return_date','return_date'];
            }
            // Always include necessary columns
            $requiredColumns = ['id'];
            $selectColumns = array_unique(array_merge($selectedColumns, $requiredColumns));
            $columns = array_diff($selectColumns,['book_number']);

            // Build the query
            $data = Bookissue::select($columns)->whereBetween('return_date', [$from, $to]);

            // Return the DataTable
            return Datatables::of($data)
                ->addColumn('booklist_id', function ($data) {
                    return $data->booklist->title ?? 'N/A'; // Assuming booklist relation exists
                })
                ->addColumn('book_number', function ($data) {
                    return $data->booklist->book_number ?? 'N/A'; // Assuming booklist relation exists
                })
                ->editColumn('issue_date', function ($data) {
                    return $data->issue_date ?? 'N/A';
                })
                ->editColumn('estimate_return_date', function ($data) {
                    return $data->estimate_return_date ?? 'N/A';
                })
                ->editColumn('return_date', function ($data) {
                    return $data->return_date ?? 'N/A';
                })
                ->addColumn('created_by', function ($data) {
                    return $data->issueBy->name ?? 'N/A'; // Assuming issueBy relation exists
                })
                ->addColumn('user_id', function ($data) {
                    $userType = $data->user->user_type ?? 'N/A';
                    return '<span class="text-capitalize">'.e($userType).'</span>';
                })
                ->rawColumns(['user_id'])
                ->make(true);
        }catch (\Exception $e) {
            \Log::error('Error in bookIssueReportSearch: ' . $e->getMessage());
            return response()->json(['error' => 'An error occurred. Please try again later.'], 500);
        }
    }
    
    public function returnExportExcel(Request $request){ 
        $daterange = $request->date;
        $from = substr($daterange, 0, -13);
        $from = date("Y-m-d", strtotime($from));
        $to = substr($daterange, -10);
        $to = date("Y-m-d", strtotime($to));

        $selectedColumns = $request->input('selected_columns', []);
        if (empty($selectedColumns)) {
            $selectedColumns = ['user_id','booklist_id','bookmember_id','issue_date','estimate_return_date','return_date','created_by'];  
        }
        $columns = array_diff($selectedColumns, ['book_number']);
        $columns = array_merge($columns, ['id','bookmember_id']);
        $data = Bookissue::select($columns)->whereBetween('return_date', [$from, $to])->get(); 
        $subjects = ['institute name','Book Issue Return Report'];
        return Excel::download(new LibraryExport($data,$selectedColumns,$subjects), 'library.xlsx');
        
    }
    public function returnExportPDF(Request $request){
        $daterange = $request->date;
        $from = substr($daterange, 0, -13);
        $from = date("Y-m-d", strtotime($from));
        $to = substr($daterange, -10);
        $to = date("Y-m-d", strtotime($to));

        $selectedColumns = $request->input('selected_columns', []);
        if (empty($selectedColumns)) {
            $selectedColumns = ['user_id','booklist_id','bookmember_id','issue_date','estimate_return_date','return_date','created_by']; 
        }
        $columns = array_diff($selectedColumns, ['book_number']);
        $columns = array_merge($columns, ['id','bookmember_id']);
        $data = Bookissue::select($columns)->whereBetween('return_date', [$from, $to])->get();
       
        $pdf = Pdf::loadView('report.library.pdf', ['bookissues'=>$data,'columns'=>$selectedColumns,'subject'=>'Book Issue Return Report']);
 
        return response()->streamDownload(function () use ($pdf) {
            echo $pdf->stream();
        }, 'users.pdf', [
            'Content-Type' => 'application/pdf',
        ]);
    }


    //book due report
    public function bookDueReport(Request $request){
        $user_type = '';
        $date = '';
        $user_types = User::select('user_type')->distinct()->get();
        return view('report.Library.book-due-report',compact('user_types'));
    }
    public function bookDueReportSearch(Request $request){
        try {
            // Parse the date range
            $daterange = $request->date;
            $from = substr($daterange, 0, -13);
            $from = date("Y-m-d", strtotime($from));
            $to = substr($daterange, -10);
            $to = date("Y-m-d", strtotime($to));
            // dd($daterange);
            // Fetch the selected columns or set defaults
            $selectedColumns = $request->input('selected_columns', []);
            if (empty($selectedColumns)) {
                $selectedColumns = ['issue_date', 'estimate_return_date'];
            }
            // Always include necessary columns
            $requiredColumns = ['id'];
            $selectColumns = array_unique(array_merge($selectedColumns, $requiredColumns));
            $columns = array_diff($selectColumns,['book_number']);

            // Build the query
            $data = Bookissue::select($columns)
                ->whereBetween('estimate_return_date', [$from, $to])
                ->whereDate('estimate_return_date', '<', date('Y-m-d'));

            // Return the DataTable
            return Datatables::of($data)
                ->addColumn('booklist_id', function ($data) {
                    return $data->booklist->title ?? 'N/A'; // Assuming booklist relation exists
                })
                ->addColumn('book_number', function ($data) {
                    return $data->booklist->book_number ?? 'N/A'; // Assuming booklist relation exists
                })
                ->editColumn('issue_date', function ($data) {
                    return $data->issue_date ?? 'N/A';
                })
                ->editColumn('estimate_return_date', function ($data) {
                    return $data->estimate_return_date ?? 'N/A';
                })
                ->addColumn('created_by', function ($data) {
                    return $data->issueBy->name ?? 'N/A'; // Assuming issueBy relation exists
                })
                ->addColumn('user_id', function ($data) {
                    $userType = $data->user->user_type ?? 'N/A';
                    return '<span class="text-capitalize">'.e($userType).'</span>';
                })
                ->rawColumns(['user_id'])
                ->make(true);
        }catch (\Exception $e) {
            \Log::error('Error in bookIssueReportSearch: ' . $e->getMessage());
            return response()->json(['error' => 'An error occurred. Please try again later.'], 500);
        }
    }
    public function dueExportExcel(Request $request){ 
        $daterange = $request->date;
        $from = substr($daterange, 0, -13);
        $from = date("Y-m-d", strtotime($from));
        $to = substr($daterange, -10);
        $to = date("Y-m-d", strtotime($to));

        $selectedColumns = $request->input('selected_columns', []);
        if (empty($selectedColumns)) {
            $selectedColumns = ['user_id','booklist_id','bookmember_id','issue_date','estimate_return_date','created_by'];  
        }
        $columns = array_diff($selectedColumns, ['book_number']);
        $columns = array_merge($columns, ['id','bookmember_id']);
        $data = Bookissue::select($columns)
                ->whereBetween('issue_date', [$from, $to])
                ->where('status', 'issued')->get(); 
        $subjects = ['institute name','Book Due Report'];        
        return Excel::download(new LibraryExport($data,$selectedColumns,$subjects), 'library.xlsx');
        
    }
    public function dueExportPDF(Request $request){
        $daterange = $request->date;
        $from = substr($daterange, 0, -13);
        $from = date("Y-m-d", strtotime($from));
        $to = substr($daterange, -10);
        $to = date("Y-m-d", strtotime($to));

        $selectedColumns = $request->input('selected_columns', []);
        if (empty($selectedColumns)) {
            $selectedColumns = ['user_id','booklist_id','bookmember_id','issue_date','estimate_return_date','created_by']; 
        }
        $columns = array_diff($selectedColumns, ['book_number']);
        $columns = array_merge($columns, ['id','bookmember_id']);
        $data = Bookissue::select($columns)
                ->whereBetween('estimate_return_date', [$from, $to])
                ->whereDate('estimate_return_date', '<', date('Y-m-d'))->get();
       
        $pdf = Pdf::loadView('report.library.pdf', ['bookissues'=>$data,'columns'=>$selectedColumns,'subject'=>'Book Due Report']);
 
        return response()->streamDownload(function () use ($pdf) {
            echo $pdf->stream();
        }, 'users.pdf', [
            'Content-Type' => 'application/pdf',
        ]);
    }

    public function bookIssueReport(Request $request){
        $user_type = '';
        $date = '';
        $user_types = User::select('user_type')->distinct()->get();
        return view('report.Library.book-issue-report',compact('user_types'));
    }
    public function bookIssueReportSearch(Request $request){
        try {
            // Parse the date range
            $daterange = $request->date;
            $from = substr($daterange, 0, -13);
            $from = date("Y-m-d", strtotime($from));
            $to = substr($daterange, -10);
            $to = date("Y-m-d", strtotime($to));

            // Fetch the selected columns or set defaults
            $selectedColumns = $request->input('selected_columns', []);
            if (empty($selectedColumns)) {
                $selectedColumns = ['issue_date', 'estimate_return_date'];
            }
            // Always include necessary columns
            $requiredColumns = ['id'];
            $selectColumns = array_unique(array_merge($selectedColumns, $requiredColumns));
            $columns = array_diff($selectColumns,['book_number']);

            // Build the query
            $data = Bookissue::select($columns)
                ->whereBetween('issue_date', [$from, $to])
                ->where('status', 'issued');

            // Return the DataTable
            return Datatables::of($data)
                ->addColumn('booklist_id', function ($data) {
                    return $data->booklist->title ?? 'N/A'; // Assuming booklist relation exists
                })
                ->addColumn('book_number', function ($data) {
                    return $data->booklist->book_number ?? 'N/A'; // Assuming booklist relation exists
                })
                ->editColumn('issue_date', function ($data) {
                    return $data->issue_date ?? 'N/A';
                })
                ->editColumn('estimate_return_date', function ($data) {
                    return $data->estimate_return_date ?? 'N/A';
                })
                ->addColumn('created_by', function ($data) {
                    return $data->issueBy->name ?? 'N/A'; // Assuming issueBy relation exists
                })
                ->addColumn('user_id', function ($data) {
                    $userType = $data->user->user_type ?? 'N/A';
                    return '<span class="text-capitalize">'.e($userType).'</span>';
                })
                ->rawColumns(['user_id'])
                ->make(true);
        } catch (\Exception $e) {
            \Log::error('Error in bookIssueReportSearch: ' . $e->getMessage());
            return response()->json(['error' => 'An error occurred. Please try again later.'], 500);
        }
    }
    public function exportExcel(Request $request){ 
        $daterange = $request->date;
        $from = substr($daterange, 0, -13);
        $from = date("Y-m-d", strtotime($from));
        $to = substr($daterange, -10);
        $to = date("Y-m-d", strtotime($to));

        $selectedColumns = $request->input('selected_columns', []);
        if (empty($selectedColumns)) {
            $selectedColumns = ['user_id','booklist_id','bookmember_id','issue_date','estimate_return_date','created_by'];  
        }
        $columns = array_diff($selectedColumns, ['book_number']);
        $columns = array_merge($columns, ['id','bookmember_id']);
        $data = Bookissue::select($columns)
                ->whereBetween('issue_date', [$from, $to])
                ->where('status', 'issued')->get(); 
        
        $subjects = ['institute name','Book Issue Report'];    
        return Excel::download(new LibraryExport($data,$selectedColumns,$subjects), 'library.xlsx');
    }
    public function exportPDF(Request $request){
        $daterange = $request->date;
        $from = substr($daterange, 0, -13);
        $from = date("Y-m-d", strtotime($from));
        $to = substr($daterange, -10);
        $to = date("Y-m-d", strtotime($to));

        $selectedColumns = $request->input('selected_columns', []);
        if (empty($selectedColumns)) {
            $selectedColumns = ['user_id','booklist_id','bookmember_id','issue_date','estimate_return_date','created_by']; 
        }
        $columns = array_diff($selectedColumns, ['book_number']);
        $columns = array_merge($columns, ['id','bookmember_id']);
        $data = Bookissue::select($columns)
                ->whereBetween('issue_date', [$from, $to])
                ->where('status', 'issued')->get();
       
        $pdf = Pdf::loadView('report.library.pdf', ['bookissues' => $data,'columns' =>$selectedColumns,'subject'=>'Book Issue Report']);
 
        return response()->streamDownload(function () use ($pdf) {
            echo $pdf->stream();
        }, 'users.pdf', [
            'Content-Type' => 'application/pdf',
        ]);
    }   
}