<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Cash_on_delivery extends CI_Controller
{
    // Session Authoriesed
    public function __construct()
    {
        parent::__construct();
        
        $customer = $this->session->userdata('customer');
        if (empty($customer)) {
            $this->session->set_flashdata('error', 'Please login to continue.');
            redirect(base_url());
            exit;
        }
        $column['cust_id'] = $customer['cust_id'];
        $table             = 'tbl_customer';
        
        // loading common model
        $this->load->model('Common_model');
        $result = $this->Common_model->Result($column, $table);
        if ($result['cust_password'] == $customer['cust_password']) {
            $login = true;
        } else {
            $login = false;
        }
        
        if (empty($customer) || $login == false) {
            $this->session->set_flashdata('error', 'Please login to continue.');
            redirect(base_url());
            exit;
        }
    }
    
    public function index()
    {
       
       
    if(isset($_SESSION['discount_type']) && $_SESSION['discount_type']==1)   
    {
    
    if( isset($_SESSION['coupon_otp_verify']))   
    {
     if($_SESSION['coupon_otp_verify']==1)   
    {
        unset($_SESSION['coupon_otp_verify']);
        unset($_SESSION['discount_type']);
    }  
    else
    {
           $this->session->set_flashdata('error', 'Please Verify Coupon OTP');
           redirect(base_url('checkout'));
          exit;
    }
    }
     else
    {
           $this->session->set_flashdata('error', 'Please Verify Coupon OTP');
           redirect(base_url('checkout'));
          exit;
    }
    }   
       
       
       
       
        
	    $column=['id'=>1];
        // we are getting results from common modal
		$data = $this->Common_model->Result($column,'tbl_settings');
        
        if (isset($_SESSION['cart_p_name'])) {
            if (!empty($_SESSION['cart_p_name'])) {
                
                
                $i         = 1;
                $statement = $this->db->query("SELECT * FROM tbl_language");
                $result    = $statement->result_array();
                foreach ($result as $row) {
                    define('LANG_VALUE_' . $i, $row['lang_value']);
                    $i++;
                }
                
                
                if (!isset($_REQUEST['msg'])) {
                    
                    if (empty($_POST['transaction_info'])) {
                        redirect(base_url('checkout'));
                        exit;
                    } else {
                        
                        
                        $payment_date = date('Y-m-d H:i:s');
                        $payment_id   = time();
                        
                        $i = 0;
                        foreach ($_SESSION['cart_p_id'] as $key => $value) {
                            $i++;
                            $arr_cart_p_id[$i] = $value;
                        }
                        
                        $i = 0;
                        foreach ($_SESSION['cart_p_name'] as $key => $value) {
                            $i++;
                            $arr_cart_p_name[$i] = $value;
                        }
                        
                        $i = 0;
                        foreach ($_SESSION['cart_size_name'] as $key => $value) {
                            $i++;
                            $arr_cart_size_name[$i] = $value;
                        }
                        
                        $i = 0;
                        foreach ($_SESSION['cart_size_id'] as $key => $value) {
                            $i++;
                            $arr_cart_size_id[$i] = $value;
                        }
                        
                        $i = 0;
                        foreach ($_SESSION['cart_color_name'] as $key => $value) {
                            $i++;
                            $arr_cart_color_name[$i] = $value;
                        }
                        
                        $i = 0;
                        foreach ($_SESSION['cart_p_qty'] as $key => $value) {
                            $i++;
                            $arr_cart_p_qty[$i] = $value;
                        }
                        
                        $i = 0;
                        foreach ($_SESSION['cart_p_current_price'] as $key => $value) {
                            $i++;
                            $arr_cart_p_current_price[$i] = $value;
                        }
                        
                        
                        $i = 0;
                        foreach ($_SESSION['cart_p_old_price'] as $key => $value) {
                            $i++;
                            $arr_cart_p_old_price[$i] = $value;
                        }
                        
                       $i=0;
                       $tpv=0;
                        foreach($_SESSION['p_pv'] as $key => $value)
                       {
                        $i++;
                       $arr_p_pv[$i] = $value;
                    
                       }
                        
                        $i         = 0;
                        $statement = $this->db->query("SELECT * FROM tbl_product");
                        $result    = $statement->result_array();
                        foreach ($result as $row) {
                            $i++;
                            $arr_p_id[$i] = $row['p_id'];
                        }
                        
                        $i = 0;
                        
                        $ffff2=0;
                        $discounted_total=0;
                        $mrp_total=0;
                        $sub_total=0;
                        
                        foreach ($_SESSION['cart_p_id'] as $key => $value) {
                            $i++;
                            
                            if(empty($arr_p_pv[$i])) { $arr_p_pv[$i] = 0; }
                        
                            $tbl_orderdata = array(
                                'product_id' => $arr_cart_p_id[$i],
                                'product_name' => $arr_cart_p_name[$i],
                                'size' => $arr_cart_size_name[$i],
                                'color' => $arr_cart_color_name[$i],
                                'quantity' => $arr_cart_p_qty[$i],
                                'unit_price' => $arr_cart_p_current_price[$i],
                                'mrp_price' => $arr_cart_p_old_price[$i],
                                'payment_id' => $payment_id,
                                'pv' => $arr_p_pv[$i]
                                );
                            
                            $this->db->insert("tbl_order",$tbl_orderdata);
                            
                            $ffff = $arr_cart_p_old_price[$i]-$arr_cart_p_current_price[$i];
    	                    $ffff2 += $ffff*$arr_cart_p_qty[$i];
    	                    $discounted_total += $arr_cart_p_current_price[$i];
    	                    $mrp_total += $arr_cart_p_old_price[$i]*$arr_cart_p_qty[$i];
    	                    
    	                    $sub_total += $arr_cart_p_current_price[$i]*$arr_cart_p_qty[$i];
                            
                            if(isset($tr))    {
                 $tr = $tr.'<tr>
                         <td>'.$i.'</td>
                         <td>
                            '.$arr_cart_p_name[$i].'<br> Size: '.$arr_cart_size_name[$i].'
                         </td>
                         <td>Qty: '.$arr_cart_p_qty[$i].'
                         </td>
                         <td> 
                            &nbsp;&#8377;
                            '.number_format($arr_cart_p_old_price[$i],2).'
                         </td>
                         <td> 
                            &nbsp;&#8377;
                            '.number_format($ffff,2).'
                         </td>
                         <td>
                            &nbsp;&#8377;
                           '.number_format($arr_cart_p_current_price[$i]*$arr_cart_p_qty[$i],2).'
                         </td>
                      </tr>';
    }
                else{
         $tr = '<tr>
                         <td>'.$i.'</td>
                         <td>
                            '.$arr_cart_p_name[$i].'<br> Size: '.$arr_cart_size_name[$i].'
                         </td>
                         <td>Qty: '.$arr_cart_p_qty[$i].'
                         </td>
                         <td> 
                            &nbsp;&#8377;
                            '.number_format($arr_cart_p_old_price[$i],2).'
                         </td>
                         <td> 
                            &nbsp;&#8377;
                            '.number_format($ffff,2).'
                         </td>
                         <td>
                            &nbsp;&#8377;
                           '.number_format($arr_cart_p_current_price[$i]*$arr_cart_p_qty[$i],2).'
                         </td>
                      </tr>';
    }
    
                            
                            
  $amt = $_POST['amount'];
  $addon = date('Y-m-d H:i:s');
  $dmob1     = $_SESSION['customer']['cust_phone']; 
  

                            
                            $track    = 'TRCID';
                            $track1   = $track . $payment_id;
                            $dname    = $_SESSION['customer']['cust_name'];
                            $dmob     = $_SESSION['customer']['cust_phone'];
                            $demail   = $_SESSION['customer']['cust_email'];
                            $daddress = $_SESSION['customer']['cust_address'] . '<br>' . $_SESSION['customer']['cust_city'] . '<br>' . $_SESSION['customer']['cust_state'] . '<br>' . $_SESSION['customer']['cust_zip'];
                            $date     = date('d/m/Y');
                            
                            $prome = 0;
                            
                            if ($prome = $arr_cart_p_name[$i]) {
                                
                                $pro = $prome++;
                            }
                            
                            
                            // getting the currect stock of this product
                            $statement1212 = $this->db->query("SELECT * FROM tbl_product_size WHERE p_id=? AND size_id=?", array(
                                $arr_cart_p_id[$i],
                                $arr_cart_size_id[$i]
                            ));
                            $result1212    = $statement1212->result_array();
                            if(count($result1212)){
                            foreach ($result1212 as $row1212) {
                                $current_qty = $row1212['p_qty'];
                            }
                            }
                            else{
                                $this->session->set_flashdata('error', 'Order Cancled Temporarly due to "'.$arr_cart_p_name[$i].'" is Out of Stock.');
                                redirect(base_url());
                                exit;
                            }
                            
                            
                            
                            // Update the stock
                            // for($j=1;$j<=count($arr_p_id);$j++)
                            // {
                            //     if($arr_p_id[$j] == $arr_cart_p_id[$i]) 
                            //     {
                            //         $current_qty = $arr_p_qty[$j];
                            //         break;
                            //     }
                            // }
                            $final_quantity = $current_qty - $arr_cart_p_qty[$i];
                            $statement      = $this->db->query("UPDATE tbl_product_size SET p_qty=? WHERE p_id=? AND size_id=?", array(
                                $final_quantity,
                                $arr_cart_p_id[$i],
                                $arr_cart_size_id[$i]
                            ));
                            
                            
                            
                            
                            
                               $tpv +=$arr_p_pv[$i]*$arr_cart_p_qty[$i];
                        }
                        
                        $statement = $this->db->query("INSERT INTO tbl_payment (  
                                customer_id,
                                customer_name,
                                customer_email,
                                payment_date,
                                txnid, 
                                paid_amount,
                                card_number,
                                card_cvv,
                                card_month,
                                card_year,
                                bank_transaction_info,
                                payment_method,
                                payment_status,
                                shipping_status,
                                payment_id,
                                tpv,
                                dcode
                            ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", array(
                            $_SESSION['customer']['cust_id'],
                            $_SESSION['customer']['cust_name'],
                            $_SESSION['customer']['cust_email'],
                            $payment_date,
                            '',
                            $_POST['amount'],
                            'Dues',
                            '',
                            '',
                            '',
                            $_POST['transaction_info'],
                            'COD',
                            'Completed',
                            'Pending',
                            $payment_id,
                            $tpv,
                            rand(1111,9999)
                        ));
                        
                        
                        
                        
                        unset($_SESSION['cart_p_id']);
                        unset($_SESSION['cart_size_id']);
                        unset($_SESSION['cart_size_name']);
                        unset($_SESSION['cart_color_id']);
                        unset($_SESSION['cart_color_name']);
                        unset($_SESSION['cart_p_qty']);
                        unset($_SESSION['cart_p_current_price']);
                        unset($_SESSION['cart_p_old_price']);
                        unset($_SESSION['cart_p_name']);
                        unset($_SESSION['cart_p_featured_photo']);
                        
                        
                    }
                }
                
                
                // select order data for message
                $i          = 1;
                $statement1 = $this->db->query("SELECT * FROM tbl_order WHERE payment_id=?", array(
                    $payment_id
                ));
                $result1    = $statement1->result_array();
                foreach ($result1 as $row1) {
                    $total = ($row1['unit_price']) * ($row1['quantity']);
                    error_reporting(0);
                    $total1 += $total;
                }
                $pro = implode(',', $arr_cart_p_name);
                
                // this is current time stamp
                $addon = date('Y-m-d H:i:s');
                
                // select Delivery Address for this order
                $statement2222 = $this->db->query("SELECT * FROM tbl_delivery_address WHERE delivery_address_id = ?", array(
                    $_SESSION['SH_address_id']
                ));
                $result222     = $statement2222->result_array();
                foreach ($result222 as $row222) {
                    $SH_address_id = $row222['delivery_address_id'];
                    $SH_name       = $row222['name'];
                    $SH_phone      = $row222['phone'];
                    $SH_state      = $row222['state'];
                    $SH_district   = $row222['district'];
                    $SH_pin_code   = $row222['pin_code'];
                    $SH_address    = $row222['address'];
                }
                
                // if Delivery Address available then save data in   'applied_delivery_address' table
                if ($SH_address_id) {
                    $statement = $this->db->query("INSERT INTO applied_delivery_address(delivery_address_id,user_id,name,phone,state,district,pin_code,address,addon,updated,payment_id,status)VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", array(
                        $SH_address_id,
                        $_SESSION['customer']['cust_id'],
                        $SH_name,
                        $SH_phone,
                        $SH_state,
                        $SH_district,
                        $SH_pin_code,
                        $SH_address,
                        $addon,
                        $addon,
                        $payment_id,
                        '1'
                    ));
                }
                
                
                // select shipping cost for this order
                $statement4 = $this->db->query("SELECT * FROM tbl_shipping_cost_all WHERE status=? AND  min_amt <= ? AND max_amt >= ?", array(
                    1,
                    $total1,
                    $total1
                ));
                $result4    = $statement4->result_array();
                foreach ($result4 as $row4) {
                    $shipping_cost = $row4['amount'];
                }
                // if shipping cost available then save data in   'applied_shipping_cost' table
                if ($shipping_cost) {
                    $statement = $this->db->query("INSERT INTO applied_shipping_cost(shipping_cost,user_id,addon,payment_id)VALUES (?,?,?,?)", array(
                        $shipping_cost,
                        $_SESSION['customer']['cust_id'],
                        $addon,
                        $payment_id
                    ));
                }
                
                // if coupon id posted
                if (isset($_POST['coupon_id'])) {
                    $statement = $this->db->query("INSERT INTO applied_coupon (coupon_id,user_id,addon,payment_id)VALUES (?,?,?,?)", array(
                        $_POST['coupon_id'],
                        $_SESSION['customer']['cust_id'],
                        $addon,
                        $payment_id
                    ));
                }
                
                // checking coupon discount is int 
                if (isset($_POST['coupon_discount']) && !empty($_POST['coupon_discount'])) {
                    $dddd    = $_POST['coupon_discount'];
                    $total11 = $total1 + $shipping_cost - $dddd;
                } else {
                    $total11 = $total1 + $shipping_cost;
                }
                
                
                if(isset($dddd)){
                    $dddd = number_format($dddd,0);
                }
                else{
                    $dddd=0;
                }
                
                if(isset($shipping_cost)){
                    $final_tatoal = $sub_total+$shipping_cost-$dddd;
                    $shipping_cost='₹'.number_format($shipping_cost,2);
                    $dddd2 = $dddd+$ffff2;
                }
                else
                {
                    $dddd2=$dddd+$ffff2;
                    $final_tatoal = $sub_total;
                    $shipping_cost='FREE';
                }
                
                /*Adding Self Benifit in "Your Save"*/
                $pvtotal = $tpv;
                if(isset($pvtotal)) {
                    $dddd2 = $dddd2 + $pvtotal;
                    $final_tatoal = $final_tatoal - $pvtotal;
                }
                /*Adding Self Benifit in "Your Save"*/
    
                $to      = $_SESSION['customer']['cust_email'];
                $subject = "Booking Information !!";
                // $message = "<b>Order Success.</b> Your order details : $pro,Order ID : <b>$payment_id</b>,Dues Amount : $total11, Booking Method :  COD, Delivery Timing and product details will be send to you within 5 minutes. Thanks & Regards ".$data['base_name'];
                
                $message = '
                <!DOCTYPE html>
                <html lang="en">
                   <head>
                      <title>Booking Information - '.$data['base_name'].'</title>
                      <meta charset="utf-8">
                      <meta name="viewport" content="width=device-width, initial-scale=1">
                      <style>
                         *{
                         margin:0;
                         padding:0;
                         }
                         table,tr,td,th{
                             border:1px solid #ccc;
                         }
                         .Body_mail{
                            width: 100%;
                            display: block;
                            background: #fff;
                            margin: auto;
                            border-radius: 10px;
                            padding: 10px;
                            box-shadow: 0 0 10px #00066f70;
                         }
                         
                         .header_maiL{
                             font-size:15px;
                         }
                         
                         @media screen and (min-width:1000px){
                            .Body_mail{
                            width: 60%;
                         }
                         .header_maiL{
                             font-size:25px;
                         }
                         }
                      </style>
                   </head>
                   <body>
                      <div style="width:100%;font-family:verdana,sans-serif,cursive;padding-top:20px;padding-bottom:20px;">
                         <div class="Body_mail">
                            <div style="background:#fff100;width:100%;height:10vw;">
                               <div style="float:left;width:30%;">
                                  <img src="'.base_url('uploads/website/share_image/').$data['share_image'].'" style="width:10vw;" />
                               </div>
                               <div style="float:left;float: left;
                    color: #222;
                    width: 70%;
                    font-weight: bold;">
                                  <div>
                                     <b style="header_maiL">'.$data['base_name'].'</b>
                                     <br>
                                     Address : '.$data['contact_address'].'
                                     <br>Contact No.: '.$data['contact_phone'].' 
                                     <br>Email: '.$data['contact_email'].'   
                                  </div>
                               </div>
                            </div>
                            <div style="padding:20px 20px 30px 20px;background: #fdfcdb;">
                            <p><b>Dear</b>  '.$_SESSION['customer']['cust_name'].',<b style="float:right">Booking Date: '.date('d F Y').'<br> Booking Time: '.date('h:i:s A').' </b></p>
                            
                            <p><b>Greetings</b></p>
                            <br>
                            <p><b>Your Order is Success.</b></p>
                            <br>
                            <p>
                               Order ID : <b>'.$payment_id.'</b>,
                               Dues Amount : &#8377; '.number_format($final_tatoal,2).',
                               Booking Method :  COD,
                               Delivery Timing and product details will be send to you within 5 minutes.
                               Thank you for shopping with us.
                               Please Visit again <b>'.$data['base_name'].'!!</b>
                            </p>
                            <br>
                            <table style="width:100%;">
                               <thead>
                                  <tr>
                                     <th>S. No.</th>
                                     <th style="width:40%;">Perticulars</th>
                                     <th>Quantity.</th>
                                     <th>MRP Price</th>
                                     <th>Discount</th>
                                     <th>Sub Total</th>
                                  </tr>
                               </thead>
                               <tbody>
                                  
                                  '.$tr.'
                                  
                               </tbody>
                            </table>
                            <br>
                            <div style="width:100%;">
                               <div style="float:right;width:50%;">
                                  <h5>MRP Total: <strong style="float:right"> &nbsp;₹ '.number_format($mrp_total,2).'</strong></h5>
                                  <h5>Discount: <strong style="float:right"> &nbsp;₹ '.number_format($ffff2,2).'</strong></h5>
                                  <h5>Sub Total: <strong style="float:right"> &nbsp;₹ '.number_format($discounted_total,2).'</strong></h5>
                                  <h5>Shipping Cost: <strong style="float:right"> '.$shipping_cost.'</strong></h5>
                                  <h5>Coupon Discount: <strong style="float:right"> &nbsp;₹ '.number_format($dddd,2).'</strong></h5>
                                  <h3>Self Benefit : <strong style="float:right"> &nbsp;₹ '.number_format($pvtotal,2).'</strong></h3>
                                  <h3>Total Amount : <strong style="float:right"> &nbsp;₹ '.number_format($final_tatoal,2).'</strong></h3>
                                  <h6> <strong style="color:green;float:right;">You Save  &nbsp;₹ '.number_format($dddd2,2).'</strong></h6>
                               </div>
                               <strong> Important: </strong>
                               <p>
                                  Please read all terms and polices on  <a href="'.base_url().'" target="blank">'.$data['web_url'].'</a> for returns, replacement and other issues.
                               </p>
                            </div>
                            <br>
                            </div>
                         </div>
                      </div>
                   </body>
                </html>
                    ';
                    
                $this->email->from($data['contact_email'], $data['base_name']);
                $this->email->to($to);
                $this->email->cc($data['base_name']);
                $this->email->bcc($data['web_url']);
                $this->email->subject($subject);
                $this->email->message($message);
                $this->email->send();
                
                // New Order Notification For Admin!!                                
                $subject = "New Order Notification !!";
                $message = "Dear Admin, New order ID $payment_id has arrived. Please visit your panel to manage this order.";
                
                $this->email->from($data['contact_email'], $data['base_name']);
                $this->email->to($data['contact_email']);
                $this->email->cc($data['base_name']);
                $this->email->bcc($data['web_url']);
                $this->email->subject($subject);
                $this->email->message($message);
                $this->email->send();
                
                
                $sender = $data['sms_sender'];
                $username = $data['sms_user'];
                $password2 = $data['sms_pass']; 
                // New Order Notification For Admin!! 
                $number2  = $data['contact_phone'];
                
                $message2 = $subject . $message;
                $url2     = "http://buzz.azmarq.com/http-api.php?username=" . urlencode($username) . "&password=" . urlencode($password2) . "&senderid=" . urlencode($sender) . "&route=1&number=" . urlencode($number) . "&message=" . urlencode($message);
                file_get_contents($url2);
                
                //  Order Notification For User!! 
                $number  = $_SESSION['customer']['cust_phone'];
                $message = "Order Success. Your order details : $pro,Order ID : $payment_id,Dues Amount : $total11, Booking Method :  COD, Delivery Timing and product details will be send to you within 5 minutes. Thanks & Regards ".$data['base_name'];
                $url     = "http://buzz.azmarq.com/http-api.php?username=" . urlencode($username) . "&password=" . urlencode($password2) . "&senderid=" . urlencode($sender) . "&route=1&number=" . urlencode($number) . "&message=" . urlencode($message);
                file_get_contents($url);
                
                $_SESSION['order_cod']  = 1;
                $_SESSION['payment_id'] = $payment_id;
                unset($_SESSION['SH_address_id']);
                
                
                
                
                
                
                $this->session->set_flashdata('success', 'Congrats! Your Order has been Accepted..');
                ?>
                <script>localStorage.removeItem("cart");localStorage.removeItem("products");localStorage.removeItem("cart_history");window.location='<?=base_url('success_cod');?>';</script>
                <?php
                redirect(base_url('success_cod'));
            } else {
                redirect(base_url());
            }
        } else {
            redirect(base_url());
        }
        
    }
}