<?php session_start();
include ('../inc/dbcon.php');
include ('../inc/functions.php');
include ('../inc/imgpro.php');
include ('../inc/repfunctions.php');
include ('../inc/cartfunctions.php');
if(isset($_SESSION["axeslogin"]) && $_SESSION["axeslogin"] == true){
get_pagesecurity('14','creates','R');    
$_SESSION['cuPages']='sel_exchangecre.php';   
$cuPage='sel_exchangecre.php';    
$aid=$_SESSION['uid'];
$brid=$_SESSION['abrid'];    
}else{
header('Location:../index.php');
exit;    
}
$mhead='sales';
$menuh='Sales';
$phead='excre';
$page='Exchange Create';
$dtnow = date("Y-m-d h:i:s", time());
$today = strftime("%Y-%m-%d", time()); 

?>



<?php
if(isset($_POST['save_exchange'])){

    // Customer
    $cusid   = (int)$_POST['cusid'];
    $cusname = escape($_POST['cusname']);

    // Old phone
    $cuspid   = (int)$_POST['cuspid'];
    $cusname= get_fild_data('tbl_customer',$cusid,'name');
    $cusimei1 = escape($_POST['cusimei1']);
    $cusimei2 = escape($_POST['cusimei2']);
    $cusprice = (float)$_POST['cusprice'];
    $cusnote  = escape($_POST['cusnote']);

    // New phone (stock)
    
    $unqid = escape($_POST['unqid']);
    
    $selpid=escape($_POST['selpid']);
    
    $selimei1 = escape($_POST['selimei1']);
    $selimei2 = escape($_POST['selimei2']);
    $selprice = (float)$_POST['selprice'];
    $seldis   = (float)$_POST['seldis'];
    $selnote  = escape($_POST['selnote']);
    
    $extrapay  = escape($_POST['extrapay']);

    // Meta
    $apdate = escape($_POST['apdate']);
    $note   = escape($_POST['note']);
    $today  = date('Y-m-d');
    
    
    
 
    
    
     //this code for purchase product from customer
     
     
    $purinvno = gen_newinvno('tbl_purchase','PUR');
    $punqid=gen_protrucking('tbl_traproduct','GP');  
    
    $sql="INSERT INTO tbl_purchase (invno,type,supid,name,subtot,total,note,apdate,nxtduedate,rawcash,creditid,brid,uid,date) VALUES 
    ('$purinvno','CU','$cusid','$cusname','$cusprice','$cusprice','$note','$apdate',$apdate,'$cusprice','LE_2','$brid','$aid','$dtnow')";  
    $result = mysqli_query($con,$sql) or die(mysqli_error($con));
    
    $sid=$con->insert_id;   
    
    $sql="INSERT INTO tbl_traproduct (type,tid,invno,refinv,pid,unqid,colid,sizid,cost,price,p_qty,p_in,s_qty,p_out,p_loc,subtot,wday,mods,brid,pnote,uid,apdate,date) VALUES 
    ('CU','$cusid','$purinvno',NULL,'$cuspid','$punqid','0','0','$cusprice','$cusprice','1','1','0','0','0','$cusprice','365','PU','$brid','$cusnote','$aid','$apdate','$dtnow')";
    
    $result = mysqli_query($con,$sql) or die(mysqli_error($con));   
    
    
    
    $code=get_fild_data('tbl_item',$cuspid,'code').'B'.$sid;   
    $sql="INSERT INTO tbl_stock (invno,pid,unqid,code,,cost,price,wday,ofid,status) VALUES ('$invno','$pid','$unqid','$code','$cusprice','$cusprice','365',NULL,'1')";
    $result = mysqli_query($con,$sql) or die(mysqli_error($con));
    
        
    $sql="INSERT INTO tbl_serial (purinv,pid,unqid,serial,rci,brid,status) VALUES ('$purinvno','$cuspid','N/A','$cusimei1','Y',$brid,'0')";
    $result = mysqli_query($con,$sql) or die(mysqli_error($con));   
    
    
    
    
    $selinvno = gen_newinvno('tbl_sales','SEL');
    
    
    $rawcash=$cusprice+$extrapay;
    
    
    
    //this code for sales product to customer
    $sql="INSERT INTO tbl_sales (invno,type,cusid,name,subtot,less,total,note,apdate,nxtduedate,rawcash,debitid,brid,uid,date) VALUES 
    ('$selinvno','CU','$selid','$cusname','$selprice','$seldis','$selprice','$note','$apdate',$apdate,'$rawcash','LE_2','$brid','$aid','$dtnow')";  
    $result = mysqli_query($con,$sql) or die(mysqli_error($con));
    
    $sql="INSERT INTO tbl_traproduct (type,tid,invno,refinv,pid,unqid,cost,price,p_qty,p_in,s_qty,p_out,p_loc,subtot,wday,mods,brid,pnote,uid,apdate,date) VALUES 
    ('CU','$cusid','$selinvno',NULL,'$selpid','$unqid','$selprice','$selprice','0','0','1','1','0','$selprice','$wday','SE','$brid','$selnote','$aid','$apdate','$dtnow')";
    $result = mysqli_query($con,$sql) or die(mysqli_error($con));   
    
    
    $sql="UPDATE tbl_serial SET unqid='$unqid',status='1' WHERE serial='$selimei1'";
    $result = mysqli_query($con,$sql) or die(mysqli_error($con));
    $sql="INSERT INTO tbl_serialsale (invno,pid,unqid,serial,mods,dli) VALUES ('$selinvno','$selpid','$unqid','$selimei1','S','Y')";
    $result = mysqli_query($con,$sql) or die(mysqli_error($con)); 
    

    // Stock check
    // $chk = mysqli_query($con,"SELECT avqty FROM tbl_brstock WHERE id=$selpid AND avqty>0");
    // if(mysqli_num_rows($chk)==0){
    //     save_msg('w','Selected phone is out of stock!');
    //     echo "<script>window.location='sel_exchangecre.php'</script>";
    //     exit;
    // }

    // Insert exchange
    
    $excno = gen_newinvno('tbl_exchange','EXC');
     
    $sql = "INSERT INTO tbl_exchange
    (invno,cus_id,cusname,cuspid,cusimei1,cusimei2,cusprice,cusnote,
     selpid,selimei1,selimei2,selprice,seldis,selnote,
     apdate,extrapay,note,created_by,created_at,selno,purno)
    VALUES
    ('$excno',$cusid,'$cusname',$cuspid,'$cusimei1','$cusimei2',$cusprice,'$cusnote',
     $selpid,'$selimei1','$selimei2',$selprice,$seldis,'$selnote',
     '$apdate',$extrapay,'$note',$aid,'$today','$selinvno','$purinvno')";

    mysqli_query($con,$sql) or die(mysqli_error($con));

  

    write_activity($aid,'EXC','Exchange completed','Customer ID: '.$cusid);
    save_msg('s','Exchange successfully saved!');

    echo "<script>window.location='sel_exchangecre.php'</script>";
    exit;
}
?>


<?php
include('../layout/head.php');
include('../layout/header.php');
include('../layout/side_nav.php');

?>



<div class="content-wrapper">
<?php include('../layout/page_head.php'); ?>
<!-- Main content -->
<section class="content">

<div class="row">
<div class="col-md-8">
<div class="box box-solid">
<div class="box-header with-border">
<h3 class="box-title">Add Product</h3>
</div>
<div class="box-body">
<?php echo display_msg();?>  
<form action="sel_exchangecre.php" onsubmit="return validate()" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div class="col-md-12 popup_details_div">    
<div class="row">
<div class="col-md-12">
<div class="col-md-1"></div>
<div class="col-md-10">    

<div class="row">
<div class="col-md-9">    
<div class="form-group">
    <label>Customer</label>
    <div class="input-group">
        <span class="input-group-addon"><span class="fa fa-user-o"></span></span>     
        <select class="form-control select2" name="cusid" id="cusid" onchange="getunqid(this.value)">
            <option value="">-Select-</option>
                <?php									
                $querys=mysqli_query($con,"SELECT * FROM tbl_customer ORDER BY name ASC")or die(mysqli_error($con));
                while ($rows=mysqli_fetch_array($querys)){
                ?>
                  
                        <option value="<?php echo $rows['id'];?>"><?php echo $rows['code'].'-'.$rows['name'];?></option>    
           
                <?php } ?>
        </select>
        <span class="input-group-addon"><a id="addsup"><span class="fa fa-plus"></span></a></span>    
    </div>    
</div>
</div>
<div class="col-md-3">    
    <div class="form-group">
        <label>Exchange Date</label>
        <input type="text" class="form-control datetimepicker" name="apdate" id="apdate" value="<?php echo $today;?>" placeholder="Exchange Date" autocomplete="off" readonly>
    </div>
</div>    
</div>    



<div class="row">
    <div class="col-md-4">    
        <div class="form-group">
            <label>Old Phone</label>
            <div class="input-group">    
                <select class="form-control select2" name="cuspid" id="cuspid" required>
                    <option value="">-Select-</option>
                    <?php									    
                    $querys=mysqli_query($con,"SELECT id,name,code FROM tbl_item where pmod!=0 ORDER BY name ASC")or die(mysqli_error($con));
                    while ($rows=mysqli_fetch_array($querys)){
                    ?>
                    <option value="<?php echo $rows['id'];?>">
                        <?php echo $rows['code'].' - '.$rows['name'];?>
                    </option>
                    <?php } ?>
                </select>
                <span class="input-group-addon">
                    <a id="additem"><span class="fa fa-plus"></span></a>
                </span>     
            </div>    
        </div>
    </div>

    <div class="col-md-4">    
        <div class="form-group">
            <label>Old Phone IMEI 1</label>
            <input type="text" class="form-control" name="cusimei1" required>
        </div>
    </div>

    <div class="col-md-4">    
        <div class="form-group">
            <label>Old Phone IMEI 2</label>
            <input type="text" class="form-control" name="cusimei2">
        </div>
    </div>
</div>



<div class="row">
    <div class="col-md-4">    
        <div class="form-group">
            <label>Old Phone Price</label>
            <input type="number" step="0.01" class="form-control" name="cusprice" required>
        </div>
    </div>

    <div class="col-md-8">    
        <div class="form-group">
            <label>Old Phone Note</label>
            <input type="text" class="form-control" name="cusnote">
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-4">    
        <div class="form-group">
            <label>New Phone (Stock)</label>
            <div class="input-group">    
                <select class="form-control select2" name="selpid" id="selpid" required>
                    <option value="">-Select-</option>
                    <?php									    
                    $querys=mysqli_query($con,"SELECT tbl_brstock.pid,tbl_brstock.name,tbl_brstock.unqid,tbl_brstock.pcode FROM tbl_brstock LEFT JOIN tbl_item ON tbl_brstock.pid=tbl_item.id WHERE tbl_item.pmod!=0 AND tbl_brstock.avqty>0")or die(mysqli_error($con));
                    while ($rows=mysqli_fetch_array($querys)){
                    ?>
                    <option value="<?php echo $rows['pid'];?>">
                        <?php echo $rows['pcode'].' - '.$rows['name'];?>
                    </option>
                    <?php } ?>
                </select>
                <span class="input-group-addon">
                    <a id="addstock"><span class="fa fa-plus"></span></a>
                </span>     
            </div>    
        </div>
    </div>

    <div class="col-md-4">    
        <div class="form-group">
            <label>New Phone IMEI 1</label>
            <input type="text" class="form-control" name="selimei1" id="selimei1" required>
            <input type="hidden" class="form-control unqid" name="unqid" id="unqid" required>
        </div>
    </div>

    <div class="col-md-4">    
        <div class="form-group">
            <label>New Phone IMEI 2</label>
            <input type="text" class="form-control" name="selimei2">
        </div>
    </div>
</div>



<div class="row">
    <div class="col-md-4">    
        <div class="form-group">
            <label>New Phone Price</label>
            <input type="number" step="0.01" class="form-control selprice" name="selprice" id="selprice"  required>
        </div>
    </div>

    <div class="col-md-4">    
        <div class="form-group">
            <label>Discount</label>
            <input type="number" step="0.01" class="form-control" name="seldis" value="0">
        </div>
    </div>

    <div class="col-md-4">    
        <div class="form-group">
            <label>New Phone Note</label>
            <input type="text" class="form-control" name="selnote">
        </div>
    </div>
</div>



<div class="row">
    <div class="col-md-4">    
        <div class="form-group">
            <label>Extra Pay</label>
            <input type="number" step="0.01" class="form-control" name="extrapay" value="0">
        </div>
    </div>
</div>



<div class="row">
    <div class="col-md-12">     
        <div class="form-group">
            <label>Exchange Note</label>
            <textarea class="form-control" maxlength="250" rows="12"  id="editor_terms" name="note" placeholder="Note"></textarea>
        </div>
    </div>  
    <!--<div class="col-md-4">-->
    <!--<div class="form-group">-->
    <!--    <label>Image</label>-->
    <!--        <div style="width:120px; height:180px;">-->
    <!--            <img src="../img/product/no_image.png" id="profile-img-tag" style="width: 100%; height: 100%; object-fit: contain;">-->
    <!--        </div>-->
    <!--    <br>    -->
    <!--    <input type="file" class="btn btn-file bg-purple btn-sm" name="item" id="profile-img" accept=".png, .gif, .jpg, .jpeg">-->
        
    <!--</div>         -->
    <!--</div>    -->
</div>    
</div>    
    
<div class="col-md-1"></div>    
</div>    
</div>    
</div>
    
<div class="clearfix" ></div>
<div class="col-md-12 nopadding widgets_area"></div>    
<div class="row"style="margin-top: 15px" >
<div class="col-md-8"></div>
<div class="col-md-4 text-right" >
<input type="submit" name="save_exchange" id="submit" class="btn btn-flat bg-purple btn-sm " value="Save"/> <a href="sel_exchangelist.php" class="btn btn-flat bg-gray  ">Close</a>
</div> 
</div>     
</form>    
</div>
</div>
</div>
<div class="col-md-4">
<div class="row">
<div class="col-md-12">
<div class="box box-solid">
<div class="box-header">
<h3 class="box-title">History </h3>
</div>
<!-- /.box-header -->
<div class="box-body" >
<?php if($_SESSION['access']=='1'){echo read_activity($aid,'EXC','A');}else{echo read_activity($aid,'EXC','U');}?>
</div>
</div>
</div>
</div>
</div>
</div>

<?php include('../layout/quick.php');?>     
</section>
<!-- /.main content -->   
<?php include('../layout/rside.php'); ?> 
</div>

<?php 
include('../layout/footer.php');
?>
<!-- page script -->
<script type="text/javascript">


$(document).on('click', '#closepop', function() {
if($('.right-side').is(':visible')) { $('.right-side').toggle('slide', { direction: 'right' }, 300); }
if($('.right-side-add').is(':visible')) { $('.right-side-add').toggle('slide', { direction: 'right' }, 300); }    
});  




// function getunqid(id){
// $.ajax({
// url: 'sel_exchange.php',
// type: 'post',
// data: {unqid : id},
// success:function(data) {
// $('#unqid').value(data);
// }
// });
// };



$(document).on('change', '#selpid', function () {
id = $(this).val();
$.ajax({
    url: 'sel_exchange.php',
    type: 'post',
    data: {getprice:id},
    dataType: 'json',
    success:function(data){
    $('#unqid').val(data[0]);
    $('#selprice').val(data[1]);
    }
});   
});  




    
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
            
reader.onload = function (e) {
$('#profile-img-tag').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#profile-img").change(function(){
readURL(this);
});
$("#profile-img-tag").click(function() {
$("#profile-img").click();
});    
</script>    




<script type="text/javascript">
    var tinymce_init = {
        language: 'en',
        directionality: 'ltr',
        plugins: [
        'advlist autolink lists charmap preview hr anchor pagebreak',
        'searchreplace wordcount visualblocks visualchars code insertdatetime nonbreaking',
        'save directionality paste textcolor'
        ],
        setup: function(ed) {
            var maxlength = parseInt($("#" + (ed.id)).attr("maxlength"));
                
            ed.on("keydown", function(e) {
                if(e.keyCode == 8 || e.keyCode == 46){
                    
                }else{
                    if (CountCharacters() >= maxlength) {
                        return false;
                    }	
                }
            });
        },
        menubar:false,
        statusbar:false,
        toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | preview code',
    };

    function CountCharacters() {
        var body = tinymce.get("editor_terms").getBody();
        var content = tinymce.trim(body.innerText || body.textContent);
        return content.length;
    };
    
    tinymce.remove("#editor_terms");
    tinymce.init(
        Object.assign({}, tinymce_init, {
        selector: '#editor_terms',
        height: 100,
    })
);  


</script> 




<script>






$(function(){

    $("#selimei1").autocomplete({
        minLength: 1,
        delay: 300,

        source: function(request, response){

            var pid = $("#selpid").val(); // selected new phone

            if(pid === ''){
                return false;
            }

            $.ajax({
                url: "sel_exchange.php",
                type: "POST",
                dataType: "json",
                data: {
                    audimei: pid,
                    search: request.term
                },
                success: function(data){
                    response(data);
                }
            });
        },

        select: function(event, ui){
            $("#selimei1").val(ui.item.label);
            return false;
        }
    });

});
</script>



<!-- /page script -->

</html>  