<?php


include_once("../public/config.php");

if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: *");
    //header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    exit(0);
}
$post_data = file_get_contents("php://input");
if (empty($post_data)) {
    //for ios
    $get_request = json_decode(json_encode($_POST));
} else {
    //for android
    $get_request = json_decode($post_data);
}
########################################################
$do = $_GET['do'];





if (empty($do)) {
// $result = date('Y-m-d H:i:s',strtotime("-1 days"));
// print_r($result);
// exit();
    //   $expenses = R::getAll("select * from   savedaily order by savedailyid  desc");
    //   $expenses = array_chunk($expenses,41);
    //   $i = 1;
    //   foreach($expenses as $expense){
          
    //       $result2 = date('Y-m-d',strtotime("-$i days"));
    //       $result = date('Y-m-d H:i:s',strtotime("-$i days"));
    //       if($result2 == '2024-05-31'){
    //         $i2 = $i + 1;
    //         $result = date('Y-m-d H:i:s',strtotime("-$i2 days"));
    //         $i +=1;
    //       }
    //       foreach($expense as $expen){
    //             R::exec("UPDATE `savedaily` SET `savedailydate`='$result' WHERE savedailyid = ? ",[$expen['savedailyid']]);

    //       }
    //       $i += 1;
        
    //   }
      
    //   $nums = 0;
    //   foreach($expenses as $expense){
    //       if($nums % 16 == 0){
    //          echo  $nums .'<br>';
    //       }
          
    //       $nums += 1;
    //   }
    
   
}else if ($do == "register") {
    $name = isset($get_request->name) ? $get_request->name : '';
    $mobile = isset($get_request->mobile) ? $get_request->mobile : '';
    $user_name = isset($get_request->user_name) ? $get_request->user_name : '';
    $password = isset($get_request->password) ? $get_request->password : '';
    $device_id = isset($get_request->device_id) ? $get_request->device_id : '';


    if (!$name || !$mobile || !$user_name || !$password) { // || !$email
        $reason = 'ﺑﻌﺾ اﻟﺤﻘﻮﻝ اﻟﻤﻄﻠﻮﺑﺔ ﻓﺎﺭﻏﺔ';
        $status = 2; //0;
        echo json_encode(array('status' => $status, 'reason' => $reason), JSON_NUMERIC_CHECK);
        exit();
    }

    $check_username = R::count('webclients','user_name = ? AND is_active = 1', [$user_name]);
    if ($check_username > 0) {
        $reason = 'اﺳﻢ اﻟﻤﺴﺘﺨﺪﻡ ﻣﻜﺮﺭ';
        $status = 2; //4;
        echo json_encode(array('status' => $status, 'reason' => $reason), JSON_NUMERIC_CHECK);
        exit();
    }
  
    
    #phone
    $check_mobile = R::count('webclients','mobile = ? AND is_active = 1', [$mobile]);
    if ($check_mobile > 0) {
        $reason = 'ﺭﻗﻢ اﻟﻤﻮﺑﺎﻳﻞ ﻣﻜﺮﺭ';
        $status = 2; //6;
        echo json_encode(array('status' => $status, 'reason' => $reason), JSON_NUMERIC_CHECK);
        exit();
    }


   try {
        $row = R::dispense('webclients');
        $row->name = $name;
        $row->mobile = $mobile;
        $row->user_name = $user_name;
        $row->password = $password;
        $row->is_active = 1;
        $row->del = 0;
        $row->addtoday = date('Y-m-d H:i:s');
        $row->adduserid = 0;
        $row->deltoday = '';      
        $row->deluserid = '';
        $row->device_id = $device_id;
        $id = R::store($row);
        if (!empty($id)) {
            $reason = 'تم إنشاء الحساب بنجاح';
            $status = 1;
        } else {
            $reason = 'Failed';
            $status = 2;
        }
    } catch (Exception $e) {
        $reason = 'ُError';
        $status = 2; //3;
    }

    echo json_encode(array('status' => $status, 'reason' => $reason, 'webclient_id' => $id, 'name' => $name, 'mobile' => $mobile, 'user_name' => $user_name));
}else if ($do == "login") {
    $username = isset($get_request->username) ? $get_request->username : '';
    $password = isset($get_request->password) ? $get_request->password : '';
    if (!empty($username) && !empty($password)) {
        $user = R::findOne('webclients', " (user_name = '" . $username . "' or mobile = '" . $mobile . "') and password = '" . $password . "' ");
        if ($user->id > 0 && $user->is_active == 0) {
             $send_data = array("status" => 1, "reason" =>   ' ﻋﻔﻮا ﻟﻢ ﻳﺘﻢ ﺗﻔﻌﻴﻞ ﺣﺴﺎﺑﻚ ﺑﻌﺪ '  , "webclient_id" => $user->id, "name" => $user->name);
        }else if ($user->id > 0) {
            $send_data = array("status" => 1, "reason" =>   'ﺗﻢ اﻟﺪﺧﻮﻝ ﺑﻨﺠﺎﺡ'  , "webclient_id" => $user->id, "name" => $user->name);
        } else {
            $send_data = array("status" => 2, "reason" => 'بيانات  التسجيل خطأ' , "webclient_id" => 0, "name" => '');
        }
    } else {
        $send_data = array("status" => 3, "reason" => 'ﺑﻌﺾ اﻟﺤﻘﻮﻝ اﻟﻤﻄﻠﻮﺑﺔ ﻓﺎﺭﻏﺔ', "webclient_id" => 0, "name" => '');
    }

    echo json_encode($send_data);
}else if ($do == "profile") {
    $id = isset($get_request->id) ? $get_request->id : '';
    $src = Host_URL . '/upload/project/';

    if ($id) {
        $projectclient = R::getRow("select *, CONCAT('$src', webclients.filepdf) as filepdf from webclients where id = ?", [$id]);
        if ($projectclient['id']> 0) {
            echo json_encode($projectclient);
        } else {
            $send_data = array("status" => 2, "reason" => 'بيانات  التسجيل خطأ' , "webclient_id" => 0, "name" => '');
             echo json_encode($send_data);
        }
    } else {
        $send_data = array("status" => 3, "reason" => 'ﺑﻌﺾ اﻟﺤﻘﻮﻝ اﻟﻤﻄﻠﻮﺑﺔ ﻓﺎﺭﻏﺔ', "webclient_id" => 0, "name" => '');
         echo json_encode($send_data);
    }
}else if ($do == "projects") {

    $webclientid = isset($get_request->webclientid) ? $get_request->webclientid : '';
    $webclient = R::findOne('webclients', " id = ? ",[$webclientid]);
    $src = Host_URL . '/upload/project/';
    if($webclient->clientids != 0){
    $projectclients = R::getAll("select *,project.id as id, CONCAT('$src', project.image) as image, CONCAT('$src', project.filepdf) as filepdf from project
    LEFT JOIN webclientprojects ON project.id = webclientprojects.projectid where webclientprojects.webclientid = ? ", [$webclientid]);     
    }else{
    $projectclients = R::getAll("select *, CONCAT('$src', project.image) as image, CONCAT('$src', project.filepdf) as filepdf,project.id as id from project ");    
    }
    echo json_encode($projectclients);



}else if ($do == "projectReport") {
    $projectid =  isset($get_request->id) ? $get_request->id : '';
    $src = Host_URL . '/upload/project/';
    if ($projectid) {
        $project = R::getRow("select *, CONCAT('$src', project.image) as image, CONCAT('$src', project.filepdf) as filepdf from project where id = ? ", [$projectid]);
        if ($project['projectstagesdata'] == 1) {
            $projectstages  = R::getAll("select * from projectstagechosse  where projectstagechosse.projectid = ? ", [$projectid]);
            foreach ($projectstages as $key =>  $projectstage) {
                $getprojectstage = R::getRow('select * from projectstages where id = ? ', [$projectstage['projectstageid']]);
                $projectstages[$key]['projectstage'] =  $getprojectstage['name'];
                $projectstageimages = explode(',', $projectstage['projectstageimages']);
                $images = [];
                for ($i=0; $i < count($projectstageimages); $i++) { 
                   $images[] = $src.$projectstageimages[$i];
                }
                $projectstages[$key]['images'] = $images;
                $projectstagefiles = explode(',', $projectstage['projectstagefiles']);
                $oldnamefiles = explode(',', $projectstage['oldnamefiles']);
                $files = [];
                for ($i=0; $i < count($projectstagefiles); $i++) { 
                   $files[] = [ 'name' => $oldnamefiles[$i],'file' => $src.$projectstagefiles[$i]];
                }
                $projectstages[$key]['files'] = $files;
            }

        }else{
            $projectstages = [];
        }
        if ($project['projecttimetableitems'] == 1) {
            $projecttimetableitems  = R::getAll("select clause,amount,duration,startdate,enddate from projecttimetableitems where projecttimetableitems.projectid = ? ", [$projectid]);
        }else{
            $projecttimetableitems = [];
        }
        
        $project['alltotalsexpense'] = 0;
        $project['alltotalsincome'] = 0;
        if ($project['expenses'] == 1) {
            
            $expensestypeids = '0';
            $arrayexpensestypeids = [];
            $allexpensestype = [];
            $alltotals = 0;
            $alltotalvalues = 0;
            $projectexchmaterialdetails = R::getAll("select *, sum(totalbuyprice) as totals, sum(finalsupervision) as finalsupervisions from projectexchmaterialdetail  JOIN projectexchmaterial
                 ON projectexchmaterialdetail.projectexchid = projectexchmaterial.id WHERE projectexchmaterial.projectid = ?  group by projectexchmaterialdetail.expensestypeid ",[$projectid]);
            foreach ($projectexchmaterialdetails as  $projectexchmaterialdetail) {
                    $expensestypeids .= ',' . $projectexchmaterialdetail['expensestypeid'];
                    $expensestypedata = R::getRow('SELECT expensestype.* FROM `expensestype` WHERE expensestypeid = ? ',[$projectexchmaterialdetail['expensestypeid']]);
                    $expenseexchange = R::getROW("select sum(thevalue) as totals, sum(finalsupervision) as finalsupervisions from expenseexchange where del = 0 and projectid = ? and expensetype = ?  ",[$projectid, $projectexchmaterialdetail['expensestypeid']]);
                    $projectexchmaterialdetailreturn = R::getROW("select *, sum(totalbuyprice) as totals, sum(finalsupervision) as finalsupervisions from  projectexchmaterialdetailreturn  JOIN projectexchmaterialreturn
                 ON  projectexchmaterialdetailreturn.projectexchid = projectexchmaterialreturn.id WHERE projectexchmaterial.projectid = ? and projectexchmaterialdetailreturn.expensestypeid = ?    ",[$projectid, $projectexchmaterialdetail['expensestypeid']]);
                   
                   if($project['supervision_type']  == 1){
                       $finalsupervisions = 0;
                   }else{
                       $finalsupervisions =  $expenseexchange['finalsupervisions'] + $projectexchmaterialdetail['finalsupervisions'] - $projectexchmaterialdetailreturn['finalsupervisions'];
                   }
                    $totals =  $expenseexchange['totals'] + $projectexchmaterialdetail['totals'] - $projectexchmaterialdetailreturn['totals'];
                    $finalsupervisions =  $expenseexchange['finalsupervisions'] + $projectexchmaterialdetail['finalsupervisions'] - $projectexchmaterialdetailreturn['finalsupervisions'];
                     $expensestype = [
                        'expensestypeid' => $expensestypedata['expensestypeid'],
                        'expensestypename' => $expensestypedata['expensestypename'],
                        'totals' =>  $totals,
                        'finalsupervisions' =>  $finalsupervisions,
                     ];
                     $allexpensestype[] = $expensestype;
                     $alltotals +=  $totals;
                     $alltotalvalues += $finalsupervisions;
        
        
            }

             $projectexchmaterialdetailreturns = R::getAll("select *, sum(totalbuyprice) as totals, sum(finalsupervision) as finalsupervisions from projectexchmaterialdetailreturn  JOIN projectexchmaterialreturn
                 ON projectexchmaterialdetailreturn.projectexchid = projectexchmaterialreturn.id WHERE projectexchmaterialreturn.projectid = ? and projectexchmaterialdetailreturn.expensestypeid not in ($expensestypeids)  group by projectexchmaterialdetailreturn.expensestypeid ",[$projectid]);
            foreach ($projectexchmaterialdetailreturns as  $projectexchmaterialdetailreturn) {
                    $expensestypeids .= ',' . $projectexchmaterialdetailreturn['expensestypeid'];
                    $expensestypedata = R::getRow('SELECT expensestype.* FROM `expensestype` WHERE expensestypeid = ? ',[$projectexchmaterialdetailreturn['expensestypeid']]);
                    $expenseexchange = R::getROW("select sum(thevalue) as totals, sum(finalsupervision) as finalsupervisions from expenseexchange where del = 0 and projectid = ? and expensetype = ?  ",[$projectid, $projectexchmaterialdetailreturn['expensestypeid']]);
                    $totals =  $expenseexchange['totals'] - $projectexchmaterialdetailreturn['totals'];
                    $finalsupervisions =  $expenseexchange['finalsupervisions'] - $projectexchmaterialdetailreturn['finalsupervisions'];
                    if($project['supervision_type']  == 1){
                       $finalsupervisions = 0;
                   }else{
                    $finalsupervisions =  $expenseexchange['finalsupervisions'] - $projectexchmaterialdetailreturn['finalsupervisions'];
                   }
                     $expensestype = [
                        'expensestypeid' => $expensestypedata['expensestypeid'],
                        'expensestypename' => $expensestypedata['expensestypename'],
                        'totals' =>  $totals,
                        'finalsupervisions' =>  $finalsupervisions,
                     ];
                     $allexpensestype[] = $expensestype;
                     $alltotals +=  $totals;
                     $alltotalvalues += $finalsupervisions;
        
        
            }
            $expenseexchanges = R::getAll("select *, sum(thevalue) as totals, sum(finalsupervision) as finalsupervisions from expenseexchange where del = 0 and projectid = ? and expensetype not in ($expensestypeids)   group by expenseexchange.expensetype ",[$projectid]);
            foreach ($expenseexchanges as  $expenseexchange) {
                 $expensestypedata = R::getRow('SELECT expensestype.* FROM `expensestype` WHERE expensestypeid = ? ',[$expenseexchange['expensetype']]);
                   if($project['supervision_type']  == 1){
                        $expenseexchange['finalsupervisions'] = 0;
                   }
                 $expensestype = [
                    'expensestypeid' => $expensestypedata['expensestypeid'],
                    'expensestypename' => $expensestypedata['expensestypename'],
                    'totals' =>  $expenseexchange['totals'],
                    'finalsupervisions' =>  $expenseexchange['finalsupervisions'],
                 ];
                 $allexpensestype[] = $expensestype;
                 $alltotals +=  $expenseexchange['totals'];
                 $alltotalvalues += $expenseexchange['finalsupervisions'];
        
                    
            }
            
            
            $project['alltotals'] =$alltotals;
            if($project['supervision_type'] == 1){
                $project['alltotalvalues'] = $project['supervision_amount'];
            }else{
               $project['alltotalvalues'] = $alltotalvalues; 
            }



        }else{
            $allexpensestype = [];
        }
        
        
        
        if ($project['income'] == 1) {
             $clientdebtchange = R::getAll("SELECT clientdebtchangedate, clientdebtchangeamount FROM `clientdebtchange` WHERE clientid = ? and paySerialNo > 0 and del = 0  ",[$project['clientid']]);
             $project['allclientdebtchange'] = R::getCell("SELECT sum(clientdebtchangeamount) FROM `clientdebtchange` WHERE clientid = ? and paySerialNo > 0 and del = 0  ",[$project['clientid']]);
             $incomes = R::getAll("SELECT incomeName,  incomeValue FROM `income` WHERE costcenterid = ? and conditions = 0  ",[$project['costcenterid']]);
             $project['allincomeValue'] = R::getCell("SELECT sum(incomeValue) FROM `income` WHERE costcenterid = ? and conditions = 0  ",[$project['costcenterid']]);
             $project['alltotalsincome'] = $project['allclientdebtchange'] + $project['allincomeValue'];
        }else{
            $dataincomes = [];
        }
$project['endtotals'] =  ($project['alltotals'] + $project['alltotalvalues']) - $project['alltotalsincome'];

        echo json_encode(array('project' => $project, 'projectstages' => $projectstages,
        'projecttimetableitems' => $projecttimetableitems, 
        'expenses' => $allexpensestype, 
        'clientdebtchange' => $clientdebtchange, 
        'incomes' => $incomes), JSON_NUMERIC_CHECK);
    } else {
        $send_data = array("status" => 3, "reason" => 'ﺑﻌﺾ اﻟﺤﻘﻮﻝ اﻟﻤﻄﻠﻮﺑﺔ ﻓﺎﺭﻏﺔ', "webclient_id" => 0, "name" => '');
         echo json_encode($send_data);
    }
}else if ($do == "updateProfile") {
    $id = isset($get_request->id) ? $get_request->id : '';
    $name = isset($get_request->name) ? $get_request->name : '';
    $mobile = isset($get_request->mobile) ? $get_request->mobile : '';
    $user_name = isset($get_request->user_name) ? $get_request->user_name : '';
    $password = isset($get_request->password) ? $get_request->password : '';
    $device_id = isset($get_request->device_id) ? $get_request->device_id : '';

    if (!$name || !$mobile || !$user_name || !$password|| !$id) { // || !$email
        $reason = 'ﺑﻌﺾ اﻟﺤﻘﻮﻝ اﻟﻤﻄﻠﻮﺑﺔ ﻓﺎﺭﻏﺔ';
        $status = 2; //0;
        echo json_encode(array('status' => $status, 'reason' => $reason), JSON_NUMERIC_CHECK);
        exit();
    }

    $check_username = R::count('webclients','user_name = ?  and id != ?  AND is_active = 1', [$user_name, $id]);
    if ($check_username > 0) {
        $reason = 'اﺳﻢ اﻟﻤﺴﺘﺨﺪﻡ ﻣﻜﺮﺭ';
        $status = 2; //4;
        echo json_encode(array('status' => $status, 'reason' => $reason), JSON_NUMERIC_CHECK);
        exit();
    }
  
    
    #phone
    $check_mobile = R::count('webclients','mobile = ? and id != ? AND is_active = 1', [$mobile, $id]);
    if ($check_mobile > 0) {
        $reason = 'ﺭﻗﻢ اﻟﻤﻮﺑﺎﻳﻞ ﻣﻜﺮﺭ';
        $status = 2; //6;
        echo json_encode(array('status' => $status, 'reason' => $reason), JSON_NUMERIC_CHECK);
        exit();
    }


   try {
        $row = R::load('webclients',$id);
        $row->name = $name;
        $row->mobile = $mobile;
        $row->user_name = $user_name;
        $row->password = $password;
        $row->device_id = $device_id;
        $row->del = 1;
        $row->updatetoday = date("Y-m-d H:i:s");          
        $row->updateuserid = 0; 
        $id = R::store($row);
        if (!empty($id)) {
            $reason = 'تم تعديل الحساب بنجاح';
            $status = 1;
        } else {
            $reason = 'حدثا خطا اثناء التعديل';
            $status = 2;
        }
    } catch (Exception $e) {
        $reason = 'ُError';
        $status = 2; //3;
    }

    echo json_encode(array('status' => $status, 'reason' => $reason, 'webclient_id' => $id, 'name' => $name, 'mobile' => $mobile, 'user_name' => $user_name));
}else if ($do == "getProjects") {

    $webclient_id = isset($get_request->webclient_id) ? $get_request->webclient_id : '';
    $projects = R::getAll('select *, project.id as projectid from project LEFT JOIN webclientprojects ON project.id = webclientprojects.projectid where webclientprojects.webclientid = ? and project.del = 0', [$webclient_id]);
     echo json_encode($projects);
}else if ($do == "getProject") {
    $projectid = isset($get_request->projectid) ? $get_request->projectid : '';
    $src = Host_URL . '/views/default/images/webclients/';
    
    $project = R::getRow('select * from project where id = ?', [$projectid]);
    $clientdebtchanges = R::getAll('SELECT clientdebtchange.* FROM `clientdebtchange` WHERE clientid = ? and del = 0 ',[$project['clientid']]);
    $expenseexchanges = R::getAll('SELECT expenseexchange.* FROM `expenseexchange` WHERE projectid = ? and del = 0 ',[$project['id']]);
    $projectexchmaterials = R::getAll('SELECT projectexchmaterial.* FROM `projectexchmaterial` WHERE projectid = ? ',[$project['id']]);
    $projectdailyreports = R::getAll('SELECT projectdailyreports.* FROM `projectdailyreports` WHERE projectid = ? ',[$project['id']]);
    $projectmaterials = R::getAll('SELECT projectmaterials.* FROM `projectmaterials` WHERE projectid = ? ',[$project['id']]);
    foreach ($projectmaterials as $key => $projectmaterial) {
       $projectmaterial[$key]['projectmaterialdetails'] = R::getAll('SELECT projectmaterialdetails.*,productName  FROM `projectmaterialdetails` JOIN product
         ON projectmaterialdetails.productid = product.productId WHERE projectmaterialid = ? ',[$projectmaterial['id']]);
    }
    $projectstagechosses = R::getAll('SELECT projectstagechosse.*,name FROM `projectstagechosse` JOIN projectstages
         ON projectstagechosse.projectstageid = projectstages.id WHERE projectid = ? ',[$project['id']]);
    echo json_encode(array('project' => $project, 'clientdebtchanges' => $clientdebtchanges, 'expenseexchanges' => $expenseexchanges, 'projectexchmaterials' => $projectexchmaterials, 'projectdailyreports' => $projectdailyreports, 'projectmaterials' => $projectmaterials, 'projectstagechosses' => $projectstagechosses), JSON_NUMERIC_CHECK);

}