<?php

class Profit
{
    private $db_con;

    public function __construct()
    {
        global $con;
        $this->db_con = $con;
    }

    public function profit_list($input_data)
    {
        $output_message = new OutputMessage();

        $profit_details_data = $this->profit_generate($input_data);

        if (!$profit_details_data) {
            $api_output = $output_message->errorOutput('No profit found');
        } else {
            $api_output = $output_message->successOutput($profit_details_data, "profit generated successfully");
        }
        return $api_output;
    }

    private function profit_generate($input_data)
    {
        // ini_set('display_errors', 1);
        // ini_set('display_startup_errors', 1);
        // error_reporting(E_ALL);
        //ini_set('memory_limit', '512M');

        $profit_data = [];
        $tmp_sql = "";

        if ($input_data->usr_start_date != "" && $input_data->usr_end_date != "") {
            $tmp_sql = "AND DATE(complete_date) between '" . $input_data->usr_start_date . "' AND '" . $input_data->usr_end_date . "' ";
        }else{
            $prevDate = date('Y-m-d', strtotime("-15 days"));
            $nextDate = date('Y-m-d');
            $tmp_sql = "AND DATE(complete_date) between '" . $prevDate . "' AND '" . $nextDate . "' ";
        }

        // $profit_sql = "SELECT DISTINCT " . tbl_profit . ".uid as profit_id, " . tbl_profit . ".work_order_id as profit_work_order_id, " . tbl_profit . ".order_date as profit_order_date, " . tbl_profit . ".complete_date as profit_complete_date, " . tbl_profit . ".work_code as profit_work_code, " . tbl_profit . ".check_date as profit_check_date, " . tbl_profit . ".actual_amount as profit_actual_amount, " . tbl_profit . ".sub_vendor as profit_sub_vendor, " . tbl_price_list . ".amount as profit_inspector_pay FROM " . tbl_profit . " INNER join " . tbl_price_list . " on " . tbl_profit . ".work_code=" . tbl_price_list . ".work_code AND " . tbl_profit . ".zip_code=" . tbl_price_list . ".zip_code WHERE " . tbl_profit . ".status='true' ".$tmp_sql." ORDER BY " . tbl_profit . ".complete_date DESC";
        //We changed the inner join to left join just to make sure the profit and completed/work orders are equal
        //$profit_sql = "SELECT DISTINCT " . tbl_profit . ".uid as profit_id, " . tbl_profit . ".city as city, " . tbl_profit . ".zip_code as zip_code, " . tbl_profit . ".address as address, " . tbl_profit . ".work_order_id as profit_work_order_id, " . tbl_profit . ".order_date as profit_order_date, " . tbl_profit . ".complete_date as profit_complete_date, " . tbl_profit . ".work_code as profit_work_code, " . tbl_profit . ".check_date as profit_check_date, " . tbl_profit . ".actual_amount as profit_actual_amount, " . tbl_profit . ".sub_vendor as profit_sub_vendor, " . tbl_price_list . ".amount as profit_inspector_pay FROM " . tbl_profit . " INNER join " . tbl_price_list . " on " . tbl_profit . ".work_code=" . tbl_price_list . ".work_code AND " . tbl_profit . ".zip_code=" . tbl_price_list . ".zip_code WHERE " . tbl_profit . ".status='true' ".$tmp_sql." ORDER BY " . tbl_profit . ".complete_date DESC";

        //Changing query to use left join instead of inner join, May 20, 2023
        
        $profit_sql = "SELECT DISTINCT " . tbl_profit . ".uid as profit_id, " . tbl_profit . ".city as city, " . tbl_profit . ".zip_code as zip_code, " . tbl_profit . ".address as address, " . tbl_profit . ".work_order_id as profit_work_order_id, " . tbl_profit . ".order_date as profit_order_date, " . tbl_profit . ".complete_date as profit_complete_date, " . tbl_profit . ".work_code as profit_work_code, " . tbl_profit . ".check_date as profit_check_date, " . tbl_profit . ".actual_amount as profit_actual_amount, " . tbl_profit . ".sub_vendor as profit_sub_vendor, " . tbl_price_list . ".amount as profit_inspector_pay FROM " . tbl_profit . " LEFT join " . tbl_price_list . " on " . tbl_profit . ".work_code=" . tbl_price_list . ".work_code AND " . tbl_profit . ".zip_code=" . tbl_price_list . ".zip_code WHERE " . tbl_profit . ".status='true' ".$tmp_sql." ORDER BY " . tbl_profit . ".complete_date DESC";
        //echo "<pre>"; print_r($profit_sql); echo "</pre>"; die;
        $profit_query = mysqli_query($this->db_con, $profit_sql);

        // while ($profit_arr = mysqli_fetch_assoc($profit_query)) {
        //     echo "<pre>"; print_r($profit_arr); echo "</pre>";
        // }
        // die;

        while ($profit_arr = mysqli_fetch_assoc($profit_query)) {
            $tmp_name = "";
            
            if($profit_arr["profit_actual_amount"]=="" || $profit_arr["profit_actual_amount"]==null){
                $profit_arr["profit_actual_amount"]=0;
            }else{
                $profit_arr["profit_actual_amount"] = $profit_arr["profit_actual_amount"];
            }
            
            if($profit_arr["profit_inspector_pay"]=="" || $profit_arr["profit_inspector_pay"]==null){
                $profit_arr["profit_inspector_pay"]=0;
            }
            $profit_inspector_sql = "SELECT first_name, last_name FROM " . tbl_usr . " WHERE alias LIKE '%" . $profit_arr["profit_sub_vendor"] . "%'";
            $profit_inspector_query = mysqli_query($this->db_con, $profit_inspector_sql) or die($this->db_con);

            while ($profit_inspector_arr = mysqli_fetch_assoc($profit_inspector_query)) {
                $tmp_name = $profit_inspector_arr["first_name"] . " " . $profit_inspector_arr["last_name"];
            }

            if ($profit_arr["profit_inspector_pay"] !== null) {
                $tmp_profit = $profit_arr["profit_actual_amount"] - $profit_arr["profit_inspector_pay"];
            } else {
                $tmp_profit = $profit_arr["profit_actual_amount"];
            }

            if ($profit_arr["profit_check_date"] == "") {
                $tmp_pay_status = "Pending";
            } else {
                $tmp_pay_status = "Paid";
            }

            if($profit_arr["profit_actual_amount"]==""){
                $profit_arr["profit_actual_amount"]=0;
            }

            $tmp_data = [
                "id" => $profit_arr["profit_id"],
                "work_order_id" => strtoupper($profit_arr["profit_work_order_id"]),
                "order_date" => date('m/d/Y', strtotime($profit_arr["profit_order_date"])),
                "complete_date" => date('m/d/Y', strtotime($profit_arr["profit_complete_date"])),
                "work_code" => strtoupper($profit_arr["profit_work_code"]),
                "pay_status" => strtoupper($tmp_pay_status),
                "actual_amount" => number_format((float)$profit_arr["profit_actual_amount"], 2, '.', ','),
                "inspector" => strtoupper($tmp_name),
                "address" => ucwords($profit_arr['address']).', '.ucwords($profit_arr['city']),
                "zip_code" => $profit_arr['zip_code'],

                "inspector_pay" => number_format((float)$profit_arr["profit_inspector_pay"], 2, '.', ','),
                "profit" => number_format((float)$tmp_profit, 2, '.', ',')
            ];

            $profit_data[] = $tmp_data;
        }

        // echo "<pre>"; print_r($profit_data); echo "</pre>"; die;

        return $profit_data;

    }
    public function profit_download($input_data): array
    {
        $output_message = new OutputMessage();
        $tmp_profit_data = $this->profit_generate($input_data);

        $tmp_file_name = "profit-" . $input_data->usr_start_date . "-to-" . $input_data->usr_end_date;

        $tmp_title = "Profit " . date('m/d/Y', strtotime($input_data->usr_start_date)) . " - " . date('m/d/Y', strtotime($input_data->usr_end_date));

        if ($input_data->usr_download_type == "pdf") {
            $profit_file = $this->generate_profit_pdf($tmp_title, $tmp_file_name, $tmp_profit_data);
        } else {
            $profit_file = $this->create_file_csv($tmp_file_name, $tmp_profit_data);
        }

        if (!$profit_file) {
            $api_output = $output_message->errorOutput("profit send ERROR");
        } else {
            $api_output = $output_message->successOutput(report_via_url . $profit_file, "profit download successfully");
        }
        return $api_output;
    }

    private function generate_profit_pdf($file_title, $file_name, $file_data)
    {
        ini_set('memory_limit', '512M');
        $make_pdf = new MakePdf();
        $profit_lst_data = "";
        $tmp_tot_sale = 0;
        $tmp_tot_profit = 0;

        $profit_template = file_get_contents("lib/template/report/template_profit.html");
        foreach ($file_data as $single_profit) {
            $profit_lst_data .= /** @lang text */
                '<tr>
                       <td>' . $single_profit["work_order_id"] . '</td>
                       <td>' . $single_profit["order_date"] . '</td>
                       <td>' . $single_profit["complete_date"] . '</td>
                       <td>' . $single_profit["work_code"] . '</td>
                       <td>' . $single_profit["pay_status"] . '</td>
                       <td>$ ' . $single_profit["actual_amount"] . '</td>
                       <td>' . $single_profit["inspector"] . '</td>
                       <td>$' . $single_profit["inspector_pay"] . '</td>
                       <td>$' . $single_profit["profit"] . '</td>
                   </tr>';
            $tmp_tot_sale += $single_profit["actual_amount"];
            $tmp_tot_profit += $single_profit["profit"];
        }

        $profit_template = str_replace("{{profit_lst}}", $profit_lst_data, $profit_template);
        $profit_template = str_replace("{{total_sale}}", $tmp_tot_sale, $profit_template);
        $profit_template = str_replace("{{total_profit}}", $tmp_tot_profit, $profit_template);
        $profit_template = str_replace("{{order_name}}", ucwords($file_title), $profit_template);


        return $make_pdf->create_pdf($file_name, $profit_template);
    }

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

        $profit_list_data = [];

        $profit_list_details_data = $item_details->details_item_profit("uid='$input_data->profit_id' AND status='true'");

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

                if ($single_profit_list["order_date"] == "01/01/1970") {
                    $single_profit_list["order_date"] = "";
                }
                if ($single_profit_list["reassigned_date"] == "01/01/1970") {
                    $single_profit_list["reassigned_date"] = "";
                }
                if ($single_profit_list["complete_date"] == "01/01/1970") {
                    $single_profit_list["complete_date"] = "";
                }
                if ($single_profit_list["due_date"] == "01/01/1970") {
                    $single_profit_list["due_date"] = "";
                }
                if ($single_profit_list["billed_date"] == "01/01/1970") {
                    $single_profit_list["billed_date"] = "";
                }
                if ($single_profit_list["check_date"] == "01/01/1970") {
                    $single_profit_list["check_date"] = "";
                }

                $profit_list_data = $single_profit_list;
            }
            $api_output = $output_message->successOutput($profit_list_data, "profit details loaded successfully");
        } else {
            $api_output = $output_message->errorOutput("profit DETAILS ERROR");
        }

        return $api_output;
    }

    public function profit_manage($manage_type, $input_data): array
    {

        $item_manage = new ItemManage();
        $output_message = new OutputMessage();


        $profit_request_data = $item_manage->manage_item_profit($manage_type, $input_data);

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

        return $api_output;
    }

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

        //Commented on Aug 12, 2024 as we have some new columns in the new profit csv upload
        // if ($item_manage->manage_item_csv($input_data->usr_file_data, 18, "profit")) {
        if ($item_manage->manage_item_csv($input_data->usr_file_data, 19, "profit")) {
            $api_output = $output_message->successOutput("", 'File uploaded successfully');
        } else {
            $api_output = $output_message->errorOutput('File upload error!!!');
        }


        return $api_output;
    }

    private function create_file_csv($file_name, $file_data)
    {
        ini_set('memory_limit', '1024');
        ini_set('max_execution_time', '-1'); //300 seconds = 5 minutes


        $file = fopen(report_via_loc . $file_name . ".csv", 'w');

        $file_header = [
            "item_1" => "Order#",
            "item_2" => "OrderDate",
            "item_3" => "CompletedDate",
            "item_4" => "WorkCode",
            "item_5" => "PayStatus",
            "item_6" => "ActualAmountPaid",
            "item_7" => "Inspector",
            "item_8" => "InspectorPay",
            "item_9" => "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["order_date"]),
                "item_3" => strtoupper($single_data["complete_date"]),
                "item_4" => $single_data["work_code"],
                "item_5" => strtoupper($single_data["pay_status"]),
                "item_6" => strtoupper($single_data["actual_amount"]),
                "item_7" => strtoupper($single_data["inspector"]),
                "item_8" => strtoupper($single_data["inspector_pay"]),
                "item_9" => strtoupper($single_data["profit"])
            ];

            fputcsv($file, $tmp_file_data);
        }

        if (fclose($file)) {
            return $file_name . ".csv";
        } else {
            return false;
        }
    }
}