<?php
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);



// ini_set('memory_limit', '512M');
class WorkOrder
{
    public function __construct()
    {
    }

    public function work_order_list($input_data)
    {
        // ini_set('display_errors', 1);
        // ini_set('display_startup_errors', 1);
        // error_reporting(E_ALL);
        
        $output_message = new OutputMessage();
        $item_details = new ItemDetails();
        $beautify_arr = new ItemBeautify();


        $start_date = $input_data->start_date;
        $end_date = $input_data->end_date;
        $order_type = $input_data->order_type;
        $search_type = $input_data->search_type;
        $page = $input_data->page;
        $sort_by = $input_data->sort_by;
        $sort_as = $input_data->sort_as;
        $limit = 100;
        $offset = ($page - 1) * $limit;


        $where = [];
        $where_sql = "";
        $limit_sql = " LIMIT $offset, $limit";

        if (!empty($start_date) && !empty($end_date)) {
            $where[] = "(DATE(completion_date) BETWEEN '$start_date' AND '$end_date')";

        } elseif (!empty($start_date)) {
            $where[] = "(DATE(completion_date) >= '$start_date')";

        } elseif (!empty($end_date)) {
            $where[] = "(DATE(completion_date) <= '$end_date')";
        } 
        // else{
        //     $prevDate = date('Y-m-d', strtotime("-1 months"));
        //     $where[] = "(DATE(completion_date) >= '$prevDate')";
        // }

        if($order_type > 0){
            //Paid
            if($order_type == 1){
                $where[] = "(is_paid = 1)";
            }else if($order_type == 2){
                $where[] = "(is_paid = 0)";
            }
            // else if($order_type == 3){
            //     $where[] = "(b.id IS NULL)";
            // }
        }

        if (!empty($search_type)) {
            // $search_type = mysqli_real_escape_string($this->db_con, $search_type);
            $where[] = "(" .
                "a.work_order_id LIKE '%$search_type%' OR " .
                "a.work_code LIKE '%$search_type%' OR " .
                "a.alias LIKE '%$search_type%' OR " .
                "a.amount LIKE '%$search_type%' OR " .
                "a.address LIKE '%$search_type%'" .
            ")";
        }

        $order_by_sql = "ORDER BY a.completion_date DESC";
        $allowed_sort_fields = ['work_order_id', 'address', 'state', 'zip_code', 'alias', 'work_code', 'amount', 'completion_date'];
        $allowed_sort_directions = ['ASC', 'DESC'];
    
        if (in_array($sort_by, $allowed_sort_fields) && in_array($sort_as, $allowed_sort_directions)) {
            $order_by_sql = "ORDER BY a.$sort_by $sort_as";
        }


        if (!empty($where)) {
            $where_sql = implode(" AND ", $where);

            $where_sql .= " AND a.status='true' ";
        }else{
            $where_sql = " a.status='true' ";
        }




        // echo $where_sql;exit;

        $result = $item_details->work_order_list_detail($where_sql . " Group By a.id $order_by_sql", $limit_sql);

        if (count($result['list']) > 0) {
            $result['pagination']['page_size'] = $limit;
            $result['pagination']['current_page'] = $page;
            $result['pagination']['total_pages'] = ceil($result['pagination']['total_records'] / $limit);
            
            $api_output = $output_message->successOutput($result, 'All work order(s) Loaded');
        } else {
            $api_output = $output_message->errorOutput('No work order available');
        }

        return $api_output;
    }

    public function work_order_details($input_data): array
    {
        $item_details = new ItemDetails();
        $output_message = new OutputMessage();
        $beautify_arr = new ItemBeautify();

        $work_order_list_data = [];

        $work_order_list_details_data = $item_details->work_order_detail("uid='$input_data->work_id' AND status='true'");

        if (count($work_order_list_details_data) > 0) {
            foreach ($work_order_list_details_data as $single_work_order_list) {
                $single_work_order_list = $beautify_arr->beautify($single_work_order_list, ["id", "status", "date_time"]);

                $work_order_list_data = $single_work_order_list;
            }
            $api_output = $output_message->successOutput($work_order_list_data, "work order details loaded successfully");
        } else {
            $api_output = $output_message->errorOutput("work order DETAILS ERROR");
        }

        return $api_output;
    }

    public function work_order_manage($manage_type, $input_data): array
    {
        $item_manage = new ItemManage();
        $output_message = new OutputMessage();

        $work_order_request_data = $item_manage->manage_item_work_order($manage_type, $input_data);

        if ($work_order_request_data) {
            $api_output = $output_message->successOutput("", "work order " . join(" ", explode("-", $manage_type)) . " successfully");
        } else {
            $api_output = $output_message->errorOutput("work order " . join(" ", explode("-", $manage_type)) . " ERROR");
        }

        return $api_output;
    }

    public function work_order_upload($input_data): array
    {
        $item_manage = new ItemManage();
        $output_message = new OutputMessage();

        if ($item_manage->manage_item_csv($input_data->usr_file_data, 21, "work_order")) {
            $api_output = $output_message->successOutput("", 'File uploaded successfully');
        } else {
            $api_output = $output_message->errorOutput('File upload error!!!');
        }


        return $api_output;
    }


    //We are using a new function, details_item_work_order_with_inspectpr_pay for this function now, created on may 20, 2023 just to display the inspector amount in the downlaod csv. 
    //Avoiding making changes in the previous function as it's being used at many places.

    public function work_order_download($input_data): array
    {
        // ini_set('display_errors', 1);
        // ini_set('display_startup_errors', 1);
        // error_reporting(E_ALL);

        $output_message = new OutputMessage();
        $item_details = new ItemDetails();

        $start_date = $input_data->start_date;
        $end_date = $input_data->end_date;
        $order_type = $input_data->order_type;



        $where = [];
        $where_sql = "";

        if (!empty($start_date) && !empty($end_date)) {
            $where[] = "(DATE(completion_date) BETWEEN '$start_date' AND '$end_date')";

            $tmp_file_name = "work-order-" . date('m-d-Y', strtotime($start_date)) . "-" . date('m-d-Y', strtotime($end_date));

        } elseif (!empty($start_date)) {
            $where[] = "(DATE(completion_date) >= '$start_date')";
            $tmp_file_name = "work-order-from-" . date('m-d-Y', strtotime($start_date));

        } elseif (!empty($end_date)) {
            $where[] = "(DATE(completion_date) <= '$end_date')";
            $tmp_file_name = "work-order-upto-" . date('m-d-Y', strtotime($end_date));
        }else{
            $prevDate = date('Y-m-d', strtotime("-1 months"));
            $where[] = "(DATE(completion_date) >= '$prevDate')";
            $tmp_file_name = "work-order-from-" . date('m-d-Y', strtotime($prevDate));
        }

        if($order_type > 0){
            //Paid
            if($order_type == 1){
                $where[] = "(is_paid = 1)";
            }else{
                $where[] = "(is_paid = 0)";
            }
        }

        


        if (!empty($where)) {
            $where_sql = implode(" AND ", $where);
        }



        $result = $item_details->work_order_list($where_sql . " AND a.status='true' ORDER BY completion_date DESC");

        // echo '<pre>', print_r($result);exit;
        //$tmp_file_name = "work-order-" . date('m-d-Y', strtotime($input_data->usr_start_date)) . "-" . date('m-d-Y', strtotime($input_data->usr_end_date));
        if (count($result) > 0) {
           
            $report_file_status = $this->create_file_csv($tmp_file_name, $result); 
            if ($report_file_status) {
                $api_output = $output_message->successOutput(report_via_url.$tmp_file_name.".csv", "report created successfully");
            } else {
                $api_output = $output_message->errorOutput('No report created');
            }
        } else {
            $api_output = $output_message->errorOutput('No report created');
        }



        return $api_output;
    }

    private function create_file_csv($file_name, $file_data): bool
    {
        
        $file = fopen(report_via_loc . $file_name . ".csv", 'w');
        $file_header = [
            "item_1" => "Order Number",
            "item_2" => "Work Code",
            "item_3" => "Completion Date",
            "item_4" => "Vendor Total",
            "item_5" => "Performed",
            "item_6" => "Address 1",
            "item_7" => "City",
            "item_8" => "State",
            "item_9" => "Zip",
            "item_10" => "Check Date",
            "item_11" => "Inspector",
            "item_12" => "Price",
            "item_13" => "Profit",
        ];


        fputcsv($file, $file_header);

        foreach ($file_data as $single_data) {

            $tmp_file_data = [
                "item_1" => strtoupper($single_data["work_order_id"]),
                "item_2" => strtoupper($single_data["work_code"]),
                "item_3" => strtoupper($single_data["completion_date"]),
                "item_4" => $single_data["amount"],
                "item_5" => $single_data["alias"],
                "item_6" => strtoupper($single_data["address"]),
                "item_7" => strtoupper($single_data["city"]),
                "item_8" => strtoupper($single_data["state"]),
                "item_9" => $single_data["zip_code"],
                "item_10" => $single_data["check_date"],
                "item_11" => $single_data["inspector_name"],
                "item_12" => $single_data["inspector_pay"],
                "item_13" => $single_data["profit_amount"]
            ];

            fputcsv($file, $tmp_file_data);
        }

        return fclose($file);
    }

}