<?php
session_start();

require_once '../Config/Database.php';
require_once '../Model/Item.php';
require_once '../Model/ItemRequest.php';
require_once '../Model/Notification.php';
require_once '../Model/Student.php';
require_once '../Model/Employee.php';
require_once '../Model/Role.php';
require_once '../Model/RolePermission.php';
require_once '../Model/SystemPermission.php';
require_once '../Model/UserPermission.php';
$item = new Item();
$role = new Role();
$employee = new Employee();
$request = new ItemRequest();
$Student = new Student();
$notification = new Notification();
$role_permission = new RolePermission();
$system_permission = new SystemPermission();
$user_permission = new UserPermission();

$roles = $role->read_all_roles();
$requests = $request->read_all_item_requests();

$my_requests = $request->read_my_item_requests($_SESSION['employee_id']);

if(isset($_GET['all_approved_requests'])){
    echo json_encode(
        array("data"=>$requests)
    ); 
}

if(isset($_GET['emp_id'])){
    $emp_id = $_GET['emp_id'];
    $employee_requests = $request->read_my_item_requests($emp_id);
    echo json_encode(
        array("data"=>$employee_requests)
    ); 
}



if(isset($_GET['my_approved_requests'])){
    echo json_encode(
        array("data"=>$my_requests)
    ); 
}

if(isset($_POST['make_request'])){
    
    $length =  count($_POST['selected_request_items']);
    // print_r($_POST['selected_request_items']);
    // $selected_item_ids = $_POST['selected_request_items']['selected_item_ids'];
    // $selected_item_px = $_POST['selected_request_items']['selected_item_px'];
    // $selected_item_qtx = $_POST['selected_request_items']['selected_item_qtx'];
    $ids = array();
    $pxs = array();
    $qtyx = array();
    $i=0;
    foreach($_POST['selected_request_items'] as $key){
        $i++;
        if($i==1){
            foreach($key as $k=>$v){
                array_push($ids,$v);
            }
        }
        if($i==2){
            foreach($key as $k=>$v){
                array_push($pxs,$v);
            }
        }
        if($i==3){
            foreach($key as $k=>$v){
                array_push($qtyx,$v);
            }
        }
    }
    // print_r($ids);
    // print_r($pxs);
    // print_r($qtyx);
    

    $amount_due = $_POST['amount_due'];
    $request_total = $_POST['request_total'];
    $discount = $_POST['discount'];
    $commission = $_POST['commission'];
    $tax = $_POST['tax'];
    $commission_value = $commission/100*$amount_due;
    $request_Student = $_POST['request_Student'];
    $wholesale = 0;
    $hash = md5(microtime());
    $total_qty = 0;
    for($i = 0; $i < count($ids); $i++){
        $total_qty += $qtyx[$i];
    }

    for($i = 0; $i < count($ids); $i++){
        $current_item = $item->read_item($ids[$i]);
        $cp = $current_item[0]['item_wholesale_price'];
        $wholesale += $cp*$qtyx[$i];
    }    
    $Student_details = $Student->read_Student($request_Student);
    $Student_name = $Student_details[0]['Student_name'];
    $Student_company = $Student_details[0]['Student_company'];

    $request_data = array(
        "request_Student"=>$request_Student,
        "item_request_quantity"=>$total_qty,
        "item_request_amount"=>$amount_due,
        "item_request_approved"=>"No",
        "item_requested_by"=>$_SESSION['employee_id'],
        "item_request_hash"=>$hash,
        "discount"=>$discount,
        "commission"=>$commission,
        "commission_value"=>$commission_value,
        "tax"=>$tax,
        "request_total"=>$request_total,
        "item_request_wholesale_amount"=>$wholesale

    );
    $total_for_notifcation = $total_qty;
    
    $request_order_response = $request->add_item_request($request_data);
    $success = array();

    if($request_order_response){
        $item_request_detail = $request->read_item_request_hash($hash);
        $item_request_id = $item_request_detail[0]['item_request_id'];
        $data = array();
        $total_qty = 0;
        // Notification
        $employee_name = $_SESSION['employee_name'];
        $notification_message = "<strong>$employee_name</strong> has requested <strong>$total_for_notifcation</strong> items worth <strong>₵$amount_due</strong> to be sold to <strong>$Student_name</strong> from  <strong>$Student_company</strong>. Pending Approval";
        $notification_data = array(
            "notification_title"=>"New Items Request",
            "notification_message"=>$notification_message,
            "type"=>"Request",
            "type_id"=>$item_request_id
        );
        $notification->add_notification($notification_data);
        // Item Request Order
        for($i = 0; $i < count($ids); $i++){
            $total_qty += $qtyx[$i];
            $data = array(
                "qty"=>$qtyx[$i],
                "px"=>$pxs[$i],
                "item_id"=>$ids[$i],
                "item_request_id"=>$item_request_id
            );
            $success = $request->add_item_request_order($data);
        }
        
        
    }
    

    if($success){
        echo json_encode(
            array('data'=>'success')
        );

        if($roles){
            foreach($roles as $r){
                $data = $role_permission->request_sms_legit_receivers($r['role_id']);
                $employee_phone = $data[0]['employee_phone'];
                $employee_name = $data[0]['employee_name'];
                $receiver = $data[0]['employee_name'];
                $greetings = "Dear ".$employee_name.", $employee_name has requested $total_for_notifcation items worth ₵$amount_due to be sold to $Student_name from  $Student_company. Pending Approval";
                $main_sms = $greetings;
                try{
                    $response = @file_get_contents("https://sms.arkesel.com/sms/api?action=send-sms&api_key=OnY5d2pCMk1UdEV4YjhjYXY=&to=$employee_phone&from=Don&sms=$main_sms");
                    $networkIssue = FALSE;
                    if($response===FALSE){
                        $networkIssue = true;
                    }
                    // set_error_handler(Exception("Database Connection Failed"),0);
                }catch(Error $e){
                    return false;
                }   
                
        
            }
        }
        if($roles){
            foreach($roles as $r){
                $data = $user_permission->request_sms_legit_receivers($r['role_id']);
                $employee_phone = $data[0]['employee_phone'];
                $employee_name = $data[0]['employee_name'];
                $receiver = $data[0]['employee_name'];
                $greetings = "Dear ".$employee_name.", $employee_name has requested $total_for_notifcation items worth ₵$amount_due to be sold to $Student_name from  $Student_company. Pending Approval";
                $main_sms = $greetings;
                try{
                    $response = @file_get_contents("https://sms.arkesel.com/sms/api?action=send-sms&api_key=OnY5d2pCMk1UdEV4YjhjYXY=&to=$employee_phone&from=Don&sms=$main_sms");
                    $networkIssue = FALSE;
                    if($response===FALSE){
                        $networkIssue = true;
                    }
                    // set_error_handler(Exception("Database Connection Failed"),0);
                }catch(Error $e){
                    return false;
                }   
                
        
            }
        }
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
    
}


if(isset($_POST['return_items'])&&isset($_POST['selected_request_items'])){
    if($_POST['selected_request_items']){
        
        $length =  count($_POST['selected_request_items']);
        $ids = array();
        $pxs = array();
        $qtyx = array();
        $i=0;
        foreach($_POST['selected_request_items'] as $key){
            $i++;
            if($i==1){
                foreach($key as $k=>$v){
                    array_push($ids,$v);
                }
            }
            if($i==2){
                foreach($key as $k=>$v){
                    array_push($pxs,$v);
                }
            }
            if($i==3){
                foreach($key as $k=>$v){
                    array_push($qtyx,$v);
                }
            }
        }
        $total_qty = 0;
        $total_px = 0;
        $qty = 0;
        $return_total = 0;
        $amount_due = 0;
        $amount_paid = 0;
        $item_request_id = 0;
        for($i = 0; $i < count($ids); $i++){
            $total_qty += intval($qtyx[$i]);
            $total_px += $pxs[$i];
            $return_total +=intval( $total_qty)*floatval($total_px);
            $item_request_order_details =  $request->read_item_request_order_only($ids[$i]);
            $item_request_order_id = $item_request_order_details[0]['item_request_order_id'];
            $item_request_id = $item_request_order_details[0]['item_request_id'];
            $old_qty = $item_request_order_details[0]['qty'];
            $qty = intval($old_qty)-$qtyx[$i];
            $data = array(
                "qty"=>$qty,
                "px"=>$pxs[$i]
            );
            $order_key = array(
                "item_request_order_id"=>$ids[$i]
            );
            
                
            $success2 = $request->update_item_request_order($order_key,$data);
            $orders = $request->read_item_request_order($item_request_id);
            $amount_due = floatval($orders[0]['item_request_amount']);
            $amount_paid = floatval($orders[0]['amount_payed']);
            if($orders){
            foreach($orders as $order){
                $item_id = $order['item_id'];
                $order_qty = $order['qty'];
                $selected_items = $item->read_item($item_id);
                $qty = $selected_items[0]['item_quantity'];
                $item_qty = floatval($qty) + floatval($order_qty);
                $data = array(
                    "item_quantity"=>$item_qty
                );
                $key = array(
                    "item_id"=>$item_id
                );
                $item->update_item($key,$data);
                
            }
        }
            $request_data = $request->read_item_request($item_request_id);
            // $amount_due = $request_data[0]['item_request_amount'];
            $item_request_id = $request_data[0]['item_request_id'];
            $request_Student = $request_data[0]['request_Student'];
            $employee_name = $request_data[0]['employee_name'];
            $Student_name = $request_data[0]['Student_name'];
            $Student_company = $request_data[0]['Student_company'];
            $refund = $request_data[0]['refund'];
            $refund = floatval($refund)+floatval($return_total);
            $items_returned = $request_data[0]['items_returned'];
            $items_returned = floatval($items_returned)+floatval($total_qty);
            $total = floatval($amount_due)-floatval($return_total);
            
            $data_request = array(
                "item_request_amount"=>$total,
                "refund"=>$refund,
                "items_returned"=>$items_returned
            );
            $data_request_key = array(
                "item_request_id"=>$item_request_id
            );
            $success = $request->update_item_request($data_request_key,$data_request);

            

        }

            if($success&&$success){
                $notification_message = "<strong>$employee_name</strong> has returned <strong>$total_qty</strong> items worth <strong>₵$return_total</strong> to <strong>$Student_name</strong> from  <strong>$Student_company</strong>.";
                $notification_data = array(
                    "notification_title"=>"New Items Return",
                    "notification_message"=>$notification_message,
                    "type"=>"Return",
                    "type_id"=>$item_request_id
                );
                $notification->add_notification($notification_data);
                echo json_encode(
                    array('data'=>'success')
                );
            
            }else{
                echo json_encode(
                    array('data'=>'fail')
                );
            
            }
    }else{
        
        echo json_encode(
            array('data'=>'fail')
        );
    }
}



if(isset($_POST['update_request'])){
    $request_id = $_POST['request_id'];
    $request_name = $_POST['request_name'];
    $data = array(
        "request_name"=>$request_name
    );
    $key = array(
        "request_id"=>$request_id
    );
    $success = $request->update_request($key,$data);
    if($success){
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}


if(isset($_POST['remove_request'])){
    $request_id = $_POST['request_id'];
    $data = $request->remove_request($request_id);
    if(!$data){
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}

// Request Details


if(isset($_POST['get_request_details'])){
    $item_request_id = $_POST['item_request_id'];
    $data = $request->read_item_request_order($item_request_id);
    if($data){
        echo json_encode(
            array("data"=>$data)
        );
    }else{
        echo json_encode(
            array("data"=>"empty")
        );
    }
}

if(isset($_POST['approve_item_request'])){
    $item_request_id = $_POST['item_request_id'];
    $data = array(
        "item_request_approved"=>"Yes",
        "item_approved_by"=>$_SESSION['employee_id']
    );
    $key = array(
        "item_request_id"=>$item_request_id
    );
    $success = $request->update_item_request($key,$data);
    $orders = $request->read_item_request_order($item_request_id);
    
    foreach($orders as $order){
        $item_id = $order['item_id'];
        $order_qty = $order['qty'];
        $selected_items = $item->read_item($item_id);
        $qty = $selected_items[0]['item_quantity'];
        $item_qty = floatval($qty) - floatval($order_qty);
        $data = array(
            "item_quantity"=>$item_qty
        );
        $key = array(
            "item_id"=>$item_id
        );
        $item->update_item($key,$data);
    }
    $notification->remove_notification($item_request_id);
    if($success){
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}

if(isset($_POST['decline_item_request'])){
    $item_request_id = $_POST['item_request_id'];
    $success = $request->remove_item_request($item_request_id);
    $success = $request->remove_item_request_order($item_request_id);
    $success = $notification->remove_notification($item_request_id);
    if(!$success){
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}

// Invoice
if(isset($_POST['find_invoice'])){
    $item_request_id = $_POST['invoice_no'];
    $success = $request->find_invoice($item_request_id);
    if($success){
        echo json_encode(
            array('data'=>$success)
        );
    
    }else{
        echo json_encode(
            array('data'=>'null')
        );
    
    }

}

if(isset($_POST['search_invoice'])){
    $item_request_id = $_POST['invoice_no'];
    $success = $request->find_invoice($item_request_id);
    if($success){
        echo json_encode(
            array('data'=>"success")
        );
    
    }else{
        echo json_encode(
            array('data'=>'null')
        );
    
    }

}

if(isset($_POST['add_payment'])){
    $item_request_id = $_POST['invoice_no'];
    $requestDetails = $request->read_item_request($item_request_id);
    $item_request_amount = $requestDetails[0]['item_request_amount'];
    
    $amount = $_POST['amount'];
    $amount_payed = $_POST['amount_payed'];
    $amount_payed = floatval($amount)+floatval($amount_payed);
    if($amount_payed>=floatval($item_request_amount)){
        $completed = "Yes";
    }else{
        $completed = "No";
    }
    $data = array(
        "amount_payed"=>$amount_payed,
        "completed"=>$completed
    );
    $key = array(
        "item_request_id"=>$item_request_id
    );
    $installment_data = array(
        "item_request_id"=>$item_request_id,
        "amount"=>$amount,
        "amount_paid"=>$amount_payed,
    );
    $success = $request->update_item_request($key,$data);
    $success2 = $request->add_installment($installment_data);
    if($success&&$success2){
        echo json_encode(
            array(
                'data'=>'success',
                'amount_payed'=>$amount_payed
            )
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}



// Student Payment History

$Student_payment_history = array();
if(isset($_GET['cus_id'])){
    $Student_id = $_GET['cus_id'];
    $Student_payment_history = $request->read_Student_item_requests($Student_id);
    echo json_encode(
        array("data"=>$Student_payment_history)
    ); 
}