<?php
    $userData = $db->userInfoByID(USER_ID);
    if($userData['type']!=USER_TYPE_MPO){
        $base = $db->selectAll('base');
        $general->arrayIndexChange($base,'id');
    }

    $general->arrayIndexChange($base,'id');
    $types = $general->get_all_doctor_type();
    $categorys = $general->get_all_doctor_category();
    $productData = $db->getProductData(' and type='.PRODUCT_TYPE_FINISHED);
    if(isset($_GET['add'])){
        if(isset($_POST['add'])){
            $name                  = $_POST["name"];
            $mobile                  = $_POST["mobile"];
            $code                  = $_POST["code"];
            $address                  = $_POST["address"];
            if($userData['type']==USER_TYPE_MPO){
                $base_id        = $userData['base_id'];
            }
            else{
                $base_id        = intval($_POST['base_id']);   
            }

            $category                  = intval($_POST["category"]);
            $type                  = intval($_POST["type"]);
            $product               = $_POST['product']??[];
            if(empty($name)){setMessage(36,'Name');$error=fl();}
            elseif(empty($code)){setMessage(36,'Code');$error=fl();}
            elseif(strlen($code)>20){setMessage(63,'Code');$error=fl();}
            elseif($userData['type']!=USER_TYPE_MPO && $base_id<1){$error=fl(); setMessage(36,'base');}
            elseif($userData['type']!=USER_TYPE_MPO && !isset($base[$base_id])){$error=fl(); setMessage(63,'base');}
            elseif($category<1){setMessage(36,'catetory');$error=fl();}
            elseif(!isset($categorys[$category])){setMessage(63,'catetory');$error=fl();}
            elseif($type<1){setMessage(36,'type');$error=fl();}
            elseif(!isset($types[$type])){setMessage(63,'type');$error=fl();}
            else{
                $products=[];
                if(!empty($product)){
                    foreach($product as $p){
                        if(!isset($productData[$p])){
                            $error=fl();
                            setMessage(63,'Product');
                            break;
                        }
                        $products[$p]=$p;
                    }
                }
            }
            if(!isset($error)){

                $data = array(
                    'name'          =>$name,
                    'mobile'        =>$mobile,
                    'code'          =>$code,
                    'base_id'       =>$base_id,
                    'address'       =>$address,
                    'category'      =>$category,
                    'type'          =>$type,

                );
                $db->transactionStart();
                $db->arrayUserInfoAdd($data);
                $id=$db->insert('doctor',$data,true);
                if($id!=false){
                    if(!empty($products)){
                        foreach($products as $product_id){
                            $data=['doctor_id'=>$id,'product_id'=>$product_id];
                            $id=$db->insert('doctor_products',$data);
                            if(!$id){$error=fl(); setMessage(66); break;}
                        }
                    }
                }         
                else{
                    $error=fl();setMessage(66);
                }
                $ac=false;
                if(!isset($error)){
                    $ac=true;
                }
                $db->transactionStop($ac);
                if(!isset($error)){
                    $general->redirect($pUrl,29,'Doctor');
                }
            }
        }
    ?>
    <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>Doctor Add</strong>
                </h5>
            </div>
            <form method="post" action="">
                <div class="card-body">
                    <?php $general->inputBoxText('name','Name',@$_POST['name'],'y');?>
                    <?php $general->inputBoxText('mobile','Mobile',@$_POST['mobile']);?>
                    <?php $general->inputBoxText('code','Code',@$_POST['code']);?>
                    <?php $general->inputBoxTextArea('address','Address',@$_POST['address']);?>
                    <?php
                        if($userData['type']!=USER_TYPE_MPO){
                            $general->inputBoxSelect($base,'Base','base_id','id','title',@$_POST['base_id']);   
                            $customers=[] ;
                        }                  

                    ?>
                    <?php $general->inputBoxSelect($categorys,'Category','category','id','title',@$_POST['category']);?>
                    <?php $general->inputBoxSelect($types,'Type','type','id','title',@$_POST['type']);?>
                    <div class="form-group row p-10">
                        <?php
                            if(!empty($productData)){
                                foreach($productData as $p){
                                ?>
                                <div class="form-group row">
                                    <div class="form-group row">
                                        <label class="col-md-5 col-form-label" for="product-<?=$p['id']?>">
                                            <?=$p['t']?>
                                        </label>
                                        <div class="col-md-7">
                                            <input class="form-check-input" id="product-<?=$p['id']?>" type="checkbox" value="<?=$p['id']?>" name="product[]">
                                        </div>
                                    </div>
                                </div>

                                <?php 
                                }
                            }
                        ?>
                    </div>
                    <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 
    }
    elseif(isset($_GET['edit'])){
        $id = intval($_GET['edit']);
        $doctor = $db->get_rowData('doctor','id',$id);
        if(empty($doctor)){$general->redirect($pUrl,63,'Docutr');}
        elseif($userData['type']==USER_TYPE_MPO && $doctor['base_id']!=$userData['base_id']){$error=fl(); $general->redirect($pUrl,63,'base');}
        $doctor_prodcuts = $db->selectAll('doctor_products','where doctor_id='.$id);
        $general->arrayIndexChange($doctor_prodcuts,'product_id');
        if(isset($_POST['edit'])){
            $name                  = $_POST["name"];
            $mobile                  = $_POST["mobile"];
            $code                  = $_POST["code"];
            if($userData['type']!=USER_TYPE_MPO){
                $base_id        = $_POST['base_id'];
            }
            $address                  = $_POST["address"];
            $category                  = intval($_POST["category"]);
            $type                  = intval($_POST["type"]);
            $product               = $_POST['product']??[];
            if(empty($name)){setMessage(36,'Name');$error=fl();}
            elseif(empty($code)){setMessage(36,'Code');$error=fl();}
            elseif(strlen($code)>20){setMessage(63,'Code');$error=fl();}
            elseif($userData['type']!=USER_TYPE_MPO && $base_id<1){$error=fl(); setMessage(36,'base');}
            elseif($userData['type']!=USER_TYPE_MPO && !isset($base[$base_id])){$error=fl(); setMessage(63,'base');}
            elseif($category<1){setMessage(36,'catetory');$error=fl();}
            elseif(!isset($categorys[$category])){setMessage(63,'catetory');$error=fl();}
            elseif($type<1){setMessage(36,'type');$error=fl();}
            elseif(!isset($types[$type])){setMessage(63,'type');$error=fl();}
            else{
                $products=[];
                if(!empty($product)){
                    foreach($product as $p){
                        if(!isset($productData[$p])){
                            $error=fl();
                            setMessage(63,'Product');
                            break;
                        }
                        $products[$p]= $p;
                    }
                }
            }
            if(!isset($error)){

                $data = array(
                    'name'         =>$name,
                    'mobile'       =>$mobile,
                    'code'        =>$code,
                    'address'      =>$address,
                    'category'      =>$category,
                    'type'      =>$type,

                );
                if($userData['type']!=USER_TYPE_MPO){
                    $data['base_id']        = $base_id;
                }
                $where=['id'=>$id];
                $db->transactionStart();
                $db->arrayUserInfoEdit($data);
                $update=$db->update('doctor',$data,$where);
                if($update!=false){
                    if(!empty($products)){
                        foreach($products as $product_id){
                            if(isset($doctor_prodcuts[$product_id])){continue;}
                            $data=['doctor_id'=>$id,'product_id'=>$product_id];
                            $id=$db->insert('doctor_products',$data);
                            if(!$id){$error=fl(); setMessage(66); break;}
                        }
                    }
                    if(!empty($doctor_prodcuts)){
                        foreach($doctor_prodcuts as $product_id=>$p){
                            if(!isset($products[$product_id])){
                                $where=['id'=>$p['id']];
                                $delete = $db->delete('doctor_products',$where);
                                if(!$delete){$error=fl(); setMessage(66); break;}
                            }
                        }
                    }
                }         
                else{
                    $error=fl();setMessage(66);
                }
                $ac=false;
                if(!isset($error)){
                    $ac=true;
                }
                $db->transactionStop($ac);
                if(!isset($error)){
                    $general->redirect($pUrl,30,'Doctor');
                }
            }
        }
    ?>
    <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>Doctor Edit</strong>
                </h5>
            </div>
            <form method="post" action="">
                <div class="card-body">
                    <?php $general->inputBoxText('name','Name',@$doctor['name'],'y');?>
                    <?php $general->inputBoxText('mobile','Mobile',@$doctor['mobile']);?>
                    <?php $general->inputBoxText('code','Code',@$doctor['code']);?>
                    <?php
                        if($userData['type']!=USER_TYPE_MPO){
                            $general->inputBoxSelect($base,'Base','base_id','id','title',@$doctor['base_id']);   
                            $customers=[] ;
                        }                  

                    ?>
                    <?php $general->inputBoxTextArea('address','Address',@$doctor['address']);?>
                    <?php $general->inputBoxSelect($categorys,'Category','category','id','title',@$doctor['category']);?>
                    <?php $general->inputBoxSelect($types,'Type','type','id','title',@$doctor['type']);?>
                    <div class="form-group row p-10">
                        <?php
                            if(!empty($productData)){
                                foreach($productData as $p){
                                    $check = $doctor_prodcuts[$p['id']]['product_id']??0;
                                ?>
                                <div class="form-group row">
                                    <div class="form-group row">
                                        <label class="col-md-5 col-form-label" for="product-<?=$p['id']?>">
                                            <?=$p['t']?>
                                        </label>
                                        <div class="col-md-7">
                                            <input class="form-check-input" <?=$general->checked($p['id'],$check)?> id="product-<?=$p['id']?>" type="checkbox" value="<?=$p['id']?>" name="product[]">
                                        </div>
                                    </div>
                                </div>

                                <?php 
                                }
                            }
                        ?>
                    </div>
                    <div class="form-group row">
                        <div class="col-md-8">
                            <input class="btn btn-info pull-right"  type="submit" name="edit" value="Submit">
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </section>
    <?php 
    }
    else{
        $q='';
        if($userData['type']==USER_TYPE_MPO){
            $q='Where base_id='.$userData['base_id'];
        }

        $doctor=$db->selectAll('doctor',$q.' order by name asc');
        $rData=[];
        $total=0;
        if(!empty($doctor)){
            foreach($doctor as $c){
                $data=[
                    'id' => $c['code'],
                    'n' => $c['name'],
                    'm' => $c['mobile'],
                    'ad' => $c['address'],
                    't' => $types[$c['type']]['title'],
                    'c' => $categorys[$c['category']]['title'],
                    'e' => '<a class="btn btn-info" href="?'.MODULE_URL.'=doctor&edit='.$c['id'].'">Edit</a>',
                ];
                if($userData['type']!=USER_TYPE_MPO){
                    $data['base'] = $base[$c['base_id']]['title']??'';
                }
               $rData[]=$data; 
            }
        }


    ?>
    <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">
                    <a class="btn btn-info" href="<?='?'.MODULE_URL.'=doctor&add=1'?>">Add</a>
                    <strong>Doctor report</strong>
                </h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped" id="reportTable">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <?php
                                     if($userData['type']!=USER_TYPE_MPO){
                                         ?>
                                         <th>Base</th>
                                         <?php 
                                     }
                                 ?>
                                <th>Name</th>
                                <th>Mobile</th>
                                <th>Address</th>
                                <th>Category</th>
                                <th>Type</th>
                                <th>Edit</th>

                            </tr>
                        </thead>
                        <tbody>
                            <?php
                                $tBalance=0;
                                foreach($rData as $s){
                                ?>
                                <tr>
                                    <td><?php echo $s['id']?></td>
                                    <?php
                                     if($userData['type']!=USER_TYPE_MPO){
                                         ?>
                                         <td><?=$s['base']?></td>
                                         <?php 
                                     }
                                 ?>
                                    <td><?php echo $s['n']?></td>
                                    <td><?php echo $s['m']?></td>
                                    <td><?php echo $s['ad']?></td>
                                    <td><?php echo $s['c']?></td>
                                    <td><?php echo $s['t']?></td>
                                    <td><?php echo $s['e']?></td>

                                </tr>
                                <?php
                                }
                            ?>
                        </tbody>

                    </table>
                    <script>
                        $(document).ready(function () {
                            $('#reportTable thead th').each(function () {
                                var title = $(this).text();
                            });
                            var table = $('#reportTable').DataTable({

                                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
    }
?>