<?php
    $userData = $db->userInfoByID(USER_ID);

    $base = $db->selectAll('base');
    $general->arrayIndexChange($base,'id');
    $bazars = $db->selectAll('bazar','where base_id='.$userData['base_id'],'id,title,base_id');
    $general->arrayIndexChange($bazars);
    $customer_category = $db->selectAll('customer_category','where isActive=1','id,title');
    $general->arrayIndexChange($customer_category);
    if(isset($_GET['add'])){

        if(isset($_POST['add'])){

            $cName                  = $_POST["cName"];
            //$opBalance          = intval($_POST["opBalance"]);
            //$blType             = intval($_POST["blType"]);
            if($userData['type']!=USER_TYPE_MPO){
                $base_id             = intval($_POST["base_id"]);
            }
            else{
                $base_id             = $userData['base_id'];
            }
            //$cDOB                   = strtotime($_POST["cDOB"]);
            $bazar                 = $_POST["bazar"];
            $bazar_id              = intval($_POST["bazar_id"]);
            $customer_category_id   = intval($_POST["customer_category_id"]);
            $owner_name            = $_POST["owner_name"];
            $cMobile                = $_POST["cMobile"];
            $district              = $_POST["district"];
            $police_station        = $_POST["police_station"];
            $cAddress                = $_POST["cAddress"];
            $cEmail                = '';
            $due_day               = intval($_POST["due_day"]);
            $credit = $db->get_company_settings('customer_default_credit_limit');



            if(empty($cName)){setMessage(36,'Name');$error=fl();}
            elseif(empty($base_id)){setMessage(36,'MPO');$error=fl();}
            elseif($customer_category_id!=0&&!isset($customer_category[$customer_category_id])){setMessage(36,'Category');$error=fl();}
            elseif(!isset($base[$base_id])){setMessage(63,'MPO');$error=fl();}
            elseif($bazar_id>0 && !isset($bazars[$bazar_id])){$error=fl();setMessage(63,'bazar');}





            if(!isset($error)){
                $base = $base[$base_id];
                $base_data=$general->getJsonFromString($base['data']);
                $total_customer =  intval(@$base_data['total_customer']);
                $total_customer++;
                $prefix = $base['code'].'-';
                $code=$prefix.str_pad($total_customer,4,0,STR_PAD_LEFT);
                $customer_data = [
                    'credit'=>$credit,
                    'district'=>$district,
                    'police_station'=>$police_station,
                ];
                //if(intval($cDOB)==0){$cDOB=0;}
                $data = array(
                    'base_id'         =>$base_id,
                    'customer_category_id'       =>$customer_category_id,
                    'name'         =>$cName,
                    'mobile'       =>$cMobile,
                    'bazar'        =>$bazar,
                    'bazar_id'        =>$bazar_id,
                    'owner_name'        =>$owner_name,
                    'address'      =>$cAddress,
                    'email'        =>$cEmail,
                    'due_day'        =>$due_day,
                    'data'        =>json_encode($customer_data),
                    'code'          =>$code

                );
                $db->transactionStart();
                $db->arrayUserInfoAdd($data);
                $cID=$db->insert('customer',$data,true);
                if($cID!=false){
                    $base_data['total_customer']=$total_customer;
                    $data=['data'=>json_encode($base_data)];
                    $where=['id'=>$base_id];
                    $update=$db->update('base',$data,$where);
                    if(!$update){$error=fl(); setMessage(66);}

                    $db->actionLogCreate('customer_id'.$cID.'_newCustomerAdd',$data);


                }         
                else{
                    $error=fl();setMessage(66);
                }
                $ac=false;
                if(!isset($error)){
                    $ac=true;
                }
                $db->transactionStop($ac);
                if(!isset($error)){
                    if(isset($_GET['form-order'])){
                        $general->redirect(URL.'/app/?'.MODULE_URL.'=new_order&customer-id='.$cID,29,'Customer');
                    }
                    $general->redirect($pUrl,29,'Customer');
                }
            }
        }
    ?>
    <div class="row"><div class="col-lg-12"><?php show_msg();?></div></div>
    <section class="mb-4">
        <div class="card">
            <div class="card-header text-center py-3"> 
                <h5 class="mb-0 text-center">
                    <strong>Customer Add</strong>
                </h5>
            </div>
            <form method="post" action="">
                <div class="card-body">
                    <?php $general->inputBoxText('cName','Name',@$_POST['cName'],'y');?>
                    <?php $general->inputBoxText('cMobile','Mobile',@$_POST['cMobile']);?>
                    <?php $general->inputBoxSelect($customer_category,'Category','customer_category_id','id','title',@$_POST['customer_category_id']);?>
                    <?php $general->inputBoxText('owner_name','Owner Name',@$_POST['owner_name']);?>
                    <?php $general->inputBoxText('district','District',@$_POST['district']);?>
                    <?php $general->inputBoxText('police_station','Police station',@$_POST['police_station']);?>
                    <?php $general->inputBoxTextArea('cAddress','Address',@$_POST['cAddress']);?>
                    <?php
                        if($userData['type']!=USER_TYPE_MPO){
                        ?>
                        <?php $general->inputBoxSelect($base,'Base','base_id','id','title',@$_POST['base_id']);?>
                        <?php
                        }
                    ?>
                    <?php $general->inputBoxText('due_day','Due day',@$_POST['due_day']);?>
                    <?php $general->inputBoxSelect($bazars,'Bazar','bazar_id','id','title');  ?>
                    <?php $general->inputBoxText('bazar','Bazar',@$_POST['bazar']);?>
                    <div class="form-group row">
                        <div class="col-md-8">
                            <input class="btn btn-info pull-right"  type="submit" name="add" value="Submit">
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </section>
    <?php 
    }
    else{
        $q=[];
        $q[]='isActive in(1,0)';
        if($userData['type']==USER_TYPE_MPO){
            $q[]  ='base_id='.  $userData['base_id'];
        }
        $sq='where '.implode(' and ',$q);

        $customer=$db->selectAll('customer',$sq.' order by name asc');
        $rData=[];
        $total=0;
        if(!empty($customer)){
            foreach($customer as $c){
                $balance=$acc->headBalance($c['head_id']);
                $total+=$balance;
                $rData[]=[
                    'id' => $c['id'],
                    'code' => $c['code'],
                    'n' => $c['name'],
                    'mpo' => $base[$c['base_id']]['title']??'',
                    'bz' => $bazars[$c['bazar_id']]['title']??'',
                    'cc' => $customer_category[$c['customer_category_id']]['title']??'',
                    'm' => $c['mobile'],
                    'c' => $c['bazar'],
                    'ad' => $c['address'],
                    'b' => $balance,
                ];
            }
        }


    ?>
    <section class="mb-4">
        <div class="card">
            <div class="card-header text-center py-3"> 
                <h5 class="mb-0 text-center">
                    <a class="btn btn-info" href="<?='?'.MODULE_URL.'=customer&add=1'?>">Add</a>
                    <strong>Customer report</strong>
                </h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped" id="reportTable">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Name</th>
                                
                                <th>Bazar</th>
                                <th>category</th>
                                <th>Mobile</th>
                                <th>Address</th>
                                <th>Balance</th>
                                <th>Statement</th>

                            </tr>
                        </thead>
                        <tbody>
                            <?php
                                $tBalance=0;
                                foreach($rData as $s){

                                    $tBalance+=$s['b'];
                                ?>
                                <tr>
                                    <td><?= $s['code']?></td>
                                    <td><?= $s['n']?></td>
                                    
                                    
                                    <td><?= $s['cc']?></td>
                                    <td><?= $s['c']?></td>
                                    <td><?= $s['m']?></td>
                                    <td><?= $s['ad']?></td>
                                    <td ><?= $general->numberFormat($s['b']);?></td>
                                    <td><?= $s['id']?></td>
                                </tr>
                                <?php
                                }
                            ?>
                             
                        </tbody>
                        <tfoot>
                            <td>
                                <td>Total</td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td><?= $general->numberFormat($tBalance)?></td>
                                <td></td>
                            </tr>
                        </tfoot>
                        
                    </table>
                    <script>
                        $(document).ready(function () {
                            $('#reportTable thead th').each(function () {
                                var title = $(this).text();
                            });
                            var table = $('#reportTable').DataTable({
                                "columnDefs": [
                                    {
                                        className: "amount_td",
                                        targets: [6]
                                    },
                                    {
                                        targets: [7],  
                                        render: function(data, type, row) {
                                            return `<a class="btn btn-info" href="<?=URL?>/app/?mdl=customer-statement&customer-id=${row[7]}">Statement</a>`;
                                        }
                                    }
                                ],
                                paging: false,
                                initComplete: function (){
                                    this.api()
                                    .columns()
                                    .every(function () {
                                        var that = this;
                                        $('input', this.header()).on('keyup change clear', function () {
                                            if (that.search() !== this.value) {
                                                that.search(this.value).draw();
                                            }
                                        });
                                    });
                                },
                            });
                        });
                       
                    </script>
                </div>
            </div>
        </div>
    </section>
    <?php
    }
?>