<?php
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
class DebitCredit
{
    public function __construct()
    {
    }

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

        $debit_credit_data = [];

        $tmp_debit_credit_data = $item_details->details_item_debit_credit("status='true' ORDER BY id DESC");

        if (count($tmp_debit_credit_data) > 0) {
            foreach ($tmp_debit_credit_data as $single_debit_credit) {
                $usr_details_data = $item_details->details_item_user("uid='" . $single_debit_credit["inspector_id"] . "'");

                if (count($usr_details_data) > 0) {
                    foreach ($usr_details_data as $single_inspector) {
                        if(!$single_inspector["status"]){
                            $tmp_status = " (Deleted User)";
                        }else{
                            $tmp_status = "";
                        }
                        $single_debit_credit["inspector"] = strtoupper($single_inspector["first_name"] . " " . $single_inspector["last_name"].$tmp_status);
                    }
                } else {
                    $single_debit_credit["inspector"] = "";
                }

                $single_debit_credit = $beautify_arr->beautify($single_debit_credit, ["inspector_id", "date_time"]);

                $debit_credit_data[] = $single_debit_credit;
            }
            $api_output = $output_message->successOutput($debit_credit_data, 'All debit credit(s) Loaded');
        } else {
            $api_output = $output_message->errorOutput('No debit credit available');
        }

        return $api_output;
    }

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

        $debit_credit_data = [];

        $debit_credit_details_data = $item_details->details_item_debit_credit("uid='$input_data->debit_credit_id' AND status='true'");

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

                $debit_credit_data = $single_debit_credit;
            }
            $api_output = $output_message->successOutput($debit_credit_data, "User " . $input_data->type . " details loaded successfully");
        } else {
            $api_output = $output_message->errorOutput("User " . $input_data->type . " DETAILS ERROR");
        }

        return $api_output;
    }

    public function debit_credit_manage($manage_type, $input_data): array
    {
        $mail = new Mail();
        $item_details = new ItemDetails();
        $item_manage = new ItemManage();
        $output_message = new OutputMessage();
        $api_output = [];
        $tmp_debit_credit_type="";

        if ($manage_type == "delete") {
            $debit_credit_details_data = $item_details->details_item_debit_credit("uid='$input_data->debit_credit_id'");
            $tmp_debit_credit_type = $debit_credit_details_data[0]["type"];
        }
        
        $debit_credit_request_data = $item_manage->manage_item_debit_credit($manage_type, $input_data);

        if ($debit_credit_request_data) {
            if ($manage_type == "add" || $manage_type == "edit") {
                $usr_item_details = $item_details->details_item_user("uid='$input_data->usr_debit_credit_inspector_id'");
                if (count($usr_item_details) > 0) {
                    foreach ($usr_item_details as $single_inspector) {
                        $tmp_inspector_name = $single_inspector["first_name"] . " " . $single_inspector["last_name"];

                        $tmp_mail_body = "Hello, " . $tmp_inspector_name . "<br>CLT Inspection Services has issued a ";
                        $tmp_mail_body .= $input_data->usr_debit_credit_type ." of <strong>$";
                        $tmp_mail_body .= $input_data->usr_debit_credit_amount . "</strong> to you account. Comment: ";
                        $tmp_mail_body .= $input_data->usr_debit_credit_comment;



                        $send_mail_status = $mail->send_mail($single_inspector["mail"], $tmp_inspector_name, "A ".$input_data->usr_debit_credit_type." has been issued to your account", $tmp_mail_body, null, false);

                        if ($send_mail_status) {
                            $api_output = $output_message->successOutput("", $tmp_debit_credit_type . " " . $manage_type . " successfully");
                        } else {
                            $api_output = $output_message->errorOutput("Message send ERROR");
                        }
                    }
                }
            } else {
                $api_output = $output_message->successOutput("", $tmp_debit_credit_type . " " . $manage_type . " successfully");
            }
        } else {
            $api_output = $output_message->errorOutput($tmp_debit_credit_type . " " . $manage_type . " ERROR");
        }

        return $api_output;
    }

    public function download_debit_credit_csv(){
        
        // $output_message = new OutputMessage();
        // $item_details = new ItemDetails();
        // $not_paid_order_list_data = [];

        // if ($input_data->usr_paid_start_date != "" && $input_data->usr_paid_end_date != "") {
        //     $tmp_sql = "AND DATE(complete_date) between '" . $input_data->usr_paid_start_date . "' AND '" . $input_data->usr_paid_end_date . "' ";
        // }else{
        //     $tmp_sql="";
        // }


        // $not_paid_sql = "SELECT " . tbl_profit . ".sub_vendor AS not_paid_sub_vendor, " . tbl_profit . ".complete_date AS not_paid_complete_date, " . tbl_profit . ".work_order_id AS not_paid_work_order_id, " . tbl_profit . ".address AS not_paid_address, " . tbl_profit . ".zip_code AS not_paid_zip, " . tbl_profit . ".work_code AS not_paid_work_code, " . tbl_price_list . ".amount AS not_paid_amount FROM " . tbl_profit . " LEFT JOIN cltpr_price_list_tbl ON " . tbl_profit . ".work_code=" . tbl_price_list . ".work_code AND " . tbl_profit . ".zip_code=" . tbl_price_list . ".zip_code  WHERE " . tbl_profit . ".check_no='' AND " . tbl_profit . ".status='true' ".$tmp_sql." ORDER BY " . tbl_profit . ".complete_date DESC";
        
        // $not_paid_query = mysqli_query($this->db_con, $not_paid_sql);
        // while ($not_paid_arr = mysqli_fetch_assoc($not_paid_query)) {
        //     $tmp_name = "";
        //     $not_paid_inspector_sql = "SELECT first_name, last_name FROM " . tbl_usr . " WHERE alias LIKE '%" . $not_paid_arr["not_paid_sub_vendor"] . "%'";
        //     $not_paid_inspector_query = mysqli_query($this->db_con, $not_paid_inspector_sql);
        //     while ($not_paid_inspector_arr = mysqli_fetch_assoc($not_paid_inspector_query)) {
        //         $tmp_name = $not_paid_inspector_arr["first_name"] . " " . $not_paid_inspector_arr["last_name"];
        //     }

        //     if ($not_paid_arr["not_paid_amount"] == null) {
        //         $tmp_paid = number_format((float)filter_var(0, FILTER_VALIDATE_FLOAT), 2, '.', ',');
        //     } else {
        //         $tmp_paid = number_format((float)filter_var($not_paid_arr["not_paid_amount"], FILTER_VALIDATE_FLOAT), 2, '.', ',');
        //     }

        //     $tmp_data = [
        //         "inspector" => strtoupper($tmp_name),
        //         "inspector_pay" => "$ " . $tmp_paid,
        //         "completed_by" => $not_paid_arr['not_paid_sub_vendor'],
        //         "work_order_id" => strtoupper($not_paid_arr["not_paid_work_order_id"]),
        //         "complete_date"=>date("m/d/Y", strtotime($not_paid_arr["not_paid_complete_date"])),
        //         "address" => strtoupper($not_paid_arr["not_paid_address"]),
        //         "zip_code" => strtoupper($not_paid_arr["not_paid_zip"]),
        //         "state" => $item_details->get_state_from_zip($not_paid_arr["not_paid_zip"]),
        //         "work_code" => strtoupper($not_paid_arr["not_paid_work_code"]),
        //     ];

        //     $not_paid_order_list_data[] = $tmp_data;
        // }
        // $file_name =  " not paid orders " . date('m/d/Y', strtotime($input_data->usr_start_date)) . " - " . date('m/d/Y', strtotime($input_data->usr_end_date));
        
        // $file_name = "report-" . $input_data->usr_start_date . "-to-" . $input_data->usr_end_date;


        // $report_file = $this->generate_not_paid_report_csv($file_name, $not_paid_order_list_data);
        // if (!$report_file) {
        //     $api_output = $output_message->errorOutput("Report send ERROR");
        // } else {
        //     $api_output = $output_message->successOutput(report_via_url_not_paid_csv . $report_file, "Report download successfully");
        // }
        // return $api_output;


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

        $debit_credit_data = [];

        $tmp_debit_credit_data = $item_details->details_item_debit_credit("status='true' ORDER BY id DESC");

        if (count($tmp_debit_credit_data) > 0) {
            foreach ($tmp_debit_credit_data as $single_debit_credit) {
                $usr_details_data = $item_details->details_item_user("uid='" . $single_debit_credit["inspector_id"] . "'");

                if (count($usr_details_data) > 0) {
                    foreach ($usr_details_data as $single_inspector) {
                        if(!$single_inspector["status"]){
                            $tmp_status = " (Deleted User)";
                        }else{
                            $tmp_status = "";
                        }
                        $single_debit_credit["inspector"] = strtoupper($single_inspector["first_name"] . " " . $single_inspector["last_name"].$tmp_status);
                    }
                } else {
                    $single_debit_credit["inspector"] = "";
                }

                $single_debit_credit = $beautify_arr->beautify($single_debit_credit, ["inspector_id", "date_time"]);


                $tmp_data = [
                    "inspector" => strtoupper($single_debit_credit['inspector']),
                    "debit_or_credit" => ucwords($single_debit_credit['type']),
                    "amount" => "$ " . $single_debit_credit['amount'],
                    "comment" => $single_debit_credit['comment'],
                    "date"=>date("m/d/Y", strtotime($single_debit_credit["date"]))
                ];


                $debit_credit_data[] = $tmp_data;
            }

            $file_name =  "debit_credit_report_" .date('Y-m-d');
            $report_file = $this->generate_debit_credit_report_csv($file_name, $debit_credit_data);
            if (!$report_file) {
                $api_output = $output_message->errorOutput("Report send ERROR");
            } else {
                $api_output = $output_message->successOutput(report_via_url_debit_credit_csv . $report_file, "Report download successfully");
            }
            return $api_output;
                $api_output = $output_message->successOutput($debit_credit_data, 'All debit credit(s) Loaded');
            } else {
                $api_output = $output_message->errorOutput('No debit credit available');
            }

        return $api_output;
    }

    //Generate CSV Report
    public function generate_debit_credit_report_csv($file_name, $debit_credit_list_data){
        $file = fopen(report_via_loc_debit_credit_csv . $file_name . ".csv", 'w');
        
        $file_header = [
            "item_1" => "Inspector",
            "item_2" => "Debit Credit",
            "item_3" => "Amount",
            "item_4" => "Comment",
            "item_5" => "Date"
        ];
        $report_arr = $debit_credit_list_data;
        fputcsv($file, $file_header);
        foreach ($report_arr as $report_val)
        {
            fputcsv( $file, array_values( $report_val ) );
        }
        
        if (fclose($file)) {
            return $file_name . ".csv";
        } else {
            return false;
        }
    }

}
