<?php

session_start();
if(empty($_SESSION['uid'])) {
    header("location:login.php");
}


include('../../config.php');

$resp=new Response();
$debug = $GLOBALS['debugging'];
$list_of_data= [];

if(isset($_GET['type'])) { 

    $_POST = json_decode(file_get_contents('php://input'), true);

    $type = $_GET['type'];

    if($type=="change_brand_status"){

        $enable = $_POST['enable'];
        $brand_id = $_POST['brand_id'];

      
        $query="UPDATE Brand SET  enable = '$enable'   WHERE id='$brand_id'";
        
        $result = queryRunner($query);
        if($result!=null){
            
            $resp -> code = $success_code;
            $resp -> message = "succesfully Insert Data ";
           array_push( $resp -> response,
            ['last_id' => findLastInsertId()  ]);
        }
        else{
            // echo $error_code;
            $resp -> code = $error_code;
            $resp -> message = "Error Insert Data ";


        }
        
        echo json_encode($resp);
    }

    else if($type=="delete_brand_record"){
        
        $id = $_GET['id'];
        
        $query="DELETE FROM Brand WHERE id = '$id'";
        $result = queryRunner($query);
        if($result!=null){
            $resp -> code = $success_code;
            $resp -> message = "succesfully Insert Data ";
        }
        else{
            $resp -> code = $error_code;
            $resp -> message = "Error Insert Data ";
        }
        echo json_encode($resp);
        
    }
    
    else if($type == "next_page"){
        $query=$_POST['query'];
        $result = queryRunner($query);
        $brand_row="";
        while ($row = rowRetriever($result)) {
           
          
            array_push($list_of_data, [
                'id' => $row['id'] , 
                'logo' => $brand_image_path.$row['image'] , 
                'name' => $row['name'] , 
                'category_name' => $row['category_name'] , 
                'total_follwers' => $row['total_follwers'] , 
                'product_count' => $row['product_count'] , 
                'sales' => $row['sales'] , 
                'avg_ratings' => $row['avg_ratings'] , 
                'enable' => $row['enable'] 
              
               

            ]);
        }
     
        if(count($list_of_data)>0){
            
             $resp -> code = $success_code;
            $resp -> message = "succesfully Insert Data ";
            $resp -> response=$list_of_data;
      
        }
        else{
            // echo $error_code;
            $resp -> code = $error_code;
            $resp -> message = "Error Insert Data ";

        }
        // echo $brand_row;
    
        echo json_encode($resp);
    }

    else if($type == "categoryies_page"){
        $query=$_POST['query'];
        $result = queryRunner($query);
        $brand_row="";
        while ($row = rowRetriever($result)) {
           
          
            array_push($list_of_data, [
                'id' => $row['id'] , 
                'logo' => $brand_image_path.$row['image'] , 
                'name' => $row['name'] , 
                'category_name' => $row['category_name'] , 
                'total_follwers' => $row['total_follwers'] , 
                'product_count' => $row['product_count'] , 
                'sales' => $row['sales'] , 
                'avg_ratings' => $row['avg_ratings'] , 
                'enable' => $row['enable'] 
              
               

            ]);
        }
        $modified_page = str_replace("LIMIT 10","",$query);
        $result = queryRunner($modified_page);
        
        $noOfRows = countRow($result);

        if($noOfRows > 10){
          $noOfPages = $noOfRows /10;

        }
        else {
          $noOfPages = 1;
        }
      
                      
        // echo "modified: ".str_replace("LIMIT 10","",$query);
     
        if(count($list_of_data)>0){
            $resp-> pagecount =  $noOfPages;
             $resp -> code = $success_code;
            $resp -> message = "succesfully Insert Data ";
            $resp -> response=$list_of_data;
      
        }
        else{
            // echo $error_code;
            $resp -> code = $error_code;
            $resp -> message = "Error Insert Data ";

        }
        // echo $brand_row;
    
        echo json_encode($resp);
    }
  
    

}
else {
    $type = $_POST['type'];

    $brand_id = isEmpty($_POST['brand_id']);
    $bank_detail_id = isEmpty($_POST['bank_detail_id']);
    $person_detail_id = isEmpty($_POST['person_detail_id']);
    $brand_crand_id = isEmpty($_POST['brand_crand_id']);


    $brand_owner_email = isEmpty($_POST['brand_crandential_email']);

    $brand_owner_password = $_POST['brand_crandential_password'];

    $brand_cat_id = isEmpty($_POST['cat-id']);
    $brand_sub_arry = $_POST['get-array'];
    $brand_name = isEmpty($_POST['brand_name']);
    $brand_address = isEmpty($_POST['brand_address']);
    $brand_logo = isEmpty($_POST["brand_logo"]);
    $brand_cover_photo = isEmpty($_POST['brand_cover_photo']);
    $bank_name = isEmpty($_POST['bank_name']);
    $branch_code = isEmpty($_POST['branch_code']);
    $BanK_holder_name = isEmpty($_POST['BanK_holder_name']);
    $bank_account_no = isEmpty($_POST['bank_account_no']);
    $bank_iban_no = isEmpty($_POST['bank_iban_no']);
    $bank_checque_pic = isEmpty($_POST['bank_cheque_pic']);
    $personal_first_name = isEmpty($_POST['personal_first_name']);
    $personal_last_name = isEmpty($_POST['personal_last_name']);
    $personal_cnic = isEmpty($_POST['personal_cnic']);
    $personal_phone_no = isEmpty($_POST['personal_phone_no']);
    $personal_address = isEmpty($_POST['personal_address']);
    $persoanl_city = isEmpty($_POST['persoanl_city']);
    $personal_country = isEmpty($_POST['personal_country']);
    $personal_postal_code = isEmpty($_POST['personal_postal_code']);



    if($type == "add_brand"){

        $brand_image=convert_save_image_from_base64("ic_brand_logo_picture".rand().".webp",$brand_logo,$brand_image_path);
        $brand_cover=convert_save_image_from_base64("ic_brand_cover_picture".rand().".webp",$brand_cover_photo,$brand_image_path);
        $brand_cheque=convert_save_image_from_base64("ic_bank_checque_picture".rand().".webp",$bank_checque_pic,$brand_image_path);
        $query="INSERT INTO Brand (category_id,sub_category_id,name,cover_photo,image,address) 
         VALUES('$brand_cat_id','$brand_sub_arry','$brand_name','$brand_cover','$brand_image',' $brand_address')";
        
        $result = queryRunner($query);
        $brand_id=findLastInsertId();
        // echo $brand_id;
        $query="INSERT INTO BankingDetail (term_id,meta_key,bank_name,branch_code,account_holder_name,account_no,iban_no,cheque_picture) 
        VALUES('$brand_id','brand detail','$bank_name','$branch_code','$BanK_holder_name',' $bank_account_no','$bank_iban_no','$brand_cheque')";
        $result = queryRunner($query);
        $query="INSERT INTO PersonalDetail (term_id,first_name,last_name,cnic,phone_no,address,city,postal_code,country) 
        VALUES('$brand_id','$personal_first_name','$personal_last_name','$personal_cnic','$personal_phone_no',' $personal_address','$persoanl_city','$personal_country','$personal_postal_code')";
        $result = queryRunner($query);
        if($result!=null){
            
            // echo "New record created successfully";
            session_start();
            header("location:../admin_panel/list_of_brands.php");
           
        }
        else{
          
            $resp -> code = $error_code;
            $resp -> message = dbErrorMessage();
            echo json_encode($resp);
        }
        

    }
    else {
        $query="UPDATE Brand as brand,BankingDetail as bankingdetail ,PersonalDetail as personaldetail,BrandCredentials as brandcrand
        SET brand.category_id = '$brand_cat_id', brand.sub_category_id = '$brand_sub_arry', brand.name = '$brand_name' , brand.address = '$brand_address',
        brandcrand.email ='$brand_owner_email',brandcrand.password = '$brand_owner_password',
         bankingdetail.bank_name = '$bank_name', bankingdetail.branch_code = '$branch_code', bankingdetail.account_holder_name = '$BanK_holder_name',
         bankingdetail.account_no = '$bank_account_no', bankingdetail.iban_no = '$bank_iban_no',personaldetail.first_name = '$personal_first_name',
         personaldetail.last_name = '$personal_last_name', personaldetail.cnic = '$personal_cnic', personaldetail.phone_no = '$personal_phone_no', 
         personaldetail.address = '$personal_address', personaldetail.city = '$persoanl_city', personaldetail.country = '$personal_country',
          personaldetail.postal_code = '$personal_postal_code' %s
         WHERE brand.id = '$brand_id' AND bankingdetail.id = '$bank_detail_id' AND personaldetail.id = '$person_detail_id' AND brandcrand.id = '$brand_crand_id' ";
        ///echo "Query 01 ".$query;
        
        if (!isPath($brand_logo)) {
            
            $brand_logo_name=convert_save_image_from_base64("ic_brand_picture".rand().".webp",$brand_logo,$brand_image_path);
            $query = sprintf($query," , brand.image ='$brand_logo_name' %s ");
            
        }
        else{
            $query = sprintf($query," ");
        }

        if (!isPath($brand_cover_photo)) {
            
            $brand_cover_photo_name=convert_save_image_from_base64("ic_brand_cover_picture".rand().".webp",$brand_cover_photo,$brand_image_path);
            $query = sprintf($query," , brand.cover_photo ='$brand_cover_photo_name' %s ");
            
        }
        else{
            
            $query = sprintf($query," ");
            
        }

        if (!isPath($bank_checque_pic)) {
            
            $bank_checque_pic_name=convert_save_image_from_base64("ic_bank_checque_picture".rand().".webp",$bank_checque_pic,$brand_image_path);
            $query = sprintf($query," , bankingdetail.cheque_picture ='$bank_checque_pic_name'  ");
            
        }
        else{
            
            $query = sprintf($query," ");
            
        }

        $result = queryRunner($query);
        if($result!=null){
            
            // echo "New record created successfully";
            session_start();
            header("location:../admin_panel/list_of_brands.php");
           
        }
        else{
          
           session_start();
            header("location:../admin_panel/editBrand.php?id=".$brand_id);
        }

    }
}
?>