<?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)) {
   
}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 = '" . $user_name . "' 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 . '/views/default/images/webclients/';

    if ($id) {
        $projectclient = R::getRow("select *, CONCAT('$src', webclients.filepdf) as filepdf from webclients where id = ? and is_active = 1", [$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 : '';
    $src = Host_URL . '/views/default/images/projects/';
    $projectclients = R::getAll("select *, CONCAT('$src', project.image) as image from project LEFT JOIN webclientprojects ON project.id = webclientprojects.projectid where webclientprojects.webclientid = ? ", [$webclientid]);    
    echo json_encode($projectclients);

}else if ($do == "projectReport") {
    $projectid =  isset($get_request->id) ? $get_request->id : '';
    $src = Host_URL . '/views/default/images/projects/';
    if ($projectid) {
        $project = R::getRow("select *, CONCAT('$src', project.image) 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 = [];
        }
        if ($project['expenses'] == 1) {
            
            $expensestypeids = '0';
            $arrayexpensestypeids = [];
            $allexpensestype = [];
            $alltotals = 0;
            $alltotalvalues = 0;
            $projectexchmaterialdetails = R::getAll("select *, sum(pronumber * probuyprice) as totals from projectexchmaterialdetail  JOIN projectexchmaterial ON projectexchmaterialdetail.projectexchid = projectexchmaterial.id WHERE projectexchmaterial.projectid = ? $projectexchmaterialchangeQuery group by projectexchmaterialdetail.expensestypeid ",[$project['id']]);
            foreach ($projectexchmaterialdetails as  $projectexchmaterialdetail) {
                    $expensestypeids .= ',' . $projectexchmaterialdetail['expensestypeid'];
                    $expensestypedata = R::getRow('SELECT expensestype.* FROM `expensestype` WHERE expensestypeid = ? ',[$projectexchmaterialdetail['expensestypeid']]);
                    $expenseexchange = R::getcell("select *, sum(thevalue) as totals from expenseexchange where del = 0 and projectid = ? and expensetype = ? $expenseexchangeQuery ",[$project->id, $projectexchmaterialdetail['expensestypeid']]);
                    $totalend =  $expenseexchange + $projectexchmaterialdetail['totals'];
                    if ($expensestypedata['withinsupervision_ratio'] == 1) {
                         if ($expensestypedata['supervision_ratiotype'] == 1) {
                            $amount = $expensestypedata['supervision_amount'];
                            $amounttext =  'قيمة';
                         }else{
                            $amount = round(($totalend * $expensestypedata['supervision_amount']) / 100, 2);
                            $amounttext = $expensestypedata['supervision_amount'] . '%';
                         }
                     }else{
                        $amounttext = '';
                        $amount = 0;
                     }
                     $expensestype = [
                        // 'expensestypeid' => $expensestypedata['expensestypeid'],
                        'expensestypename' => $expensestypedata['expensestypename'],
                        // 'withinsupervision_ratio' => $expensestypedata['withinsupervision_ratio'],
                        // 'supervision_ratiotype' => $expensestypedata['supervision_ratiotype'],
                        // 'supervision_amount' => $expensestypedata['supervision_amount'],
                        'totalend' =>  $totalend,
                        // 'amounttext' =>  $amounttext,
                        // 'amount' => $amount,
                     ];
                     $allexpensestype[] = $expensestype;
                     $alltotals +=  $totalend;
                     $alltotalvalues += $amount;


            }

            $expenseexchange = R::getAll("select *, sum(thevalue) as totals from expenseexchange where del = 0 and projectid = ? and expensetype not in ($expensestypeids) $expenseexchangeQuery  group by expenseexchange.expensetype ",[$project['id']]);
            foreach ($expenseexchanges as  $expenseexchange) {
                 $expensestypedata = R::getRow('SELECT expensestype.* FROM `expensestype` WHERE expensestypeid = ? ',[$expenseexchange['expensetype']]);
                 $totalend = $expenseexchange['thevalue'];
                 if ($expensestypedata['withinsupervision_ratio'] == 1) {
                     if ($expensestypedata['supervision_ratiotype'] == 1) {
                        $amount = $expensestypedata['supervision_amount'];
                        $amounttext =  'قيمة';
                     }else{
                        $amount = round(($totalend * $expensestypedata['supervision_amount']) / 100, 2);
                        $amounttext = $expensestypedata['supervision_amount'] . '%';
                     }
                 }else{
                    $amounttext = '';
                    $amount = 0;
                 }
                 $expensestype = [
                    // 'expensestypeid' => $expensestypedata['expensestypeid'],
                    'expensestypename' => $expensestypedata['expensestypename'],
                    // 'withinsupervision_ratio' => $expensestypedata['withinsupervision_ratio'],
                    // 'supervision_ratiotype' => $expensestypedata['supervision_ratiotype'],
                    // 'supervision_amount' => $expensestypedata['supervision_amount'],
                    'totalend' =>  $totalend,
                    // 'amounttext' =>  $amounttext,
                    // 'amount' => $amount,
                 ];
                 $allexpensestype[] = $expensestype;
                 $alltotals +=  $totalend;
                 $alltotalvalues += $amount;

                    
            }

        }else{
            $allexpensestype = [];
        }
        if ($project['income'] == 1) {
             $dataincomes = R::getAll("SELECT clientdebtchangedate, clientdebtchangeamount FROM `clientdebtchange` WHERE clientid = ? and del = 0 $clientdebtchangeQuery ",[$project['clientid']]);
        }else{
            $dataincomes = [];
        }



        echo json_encode(array('project' => $project, 'projectstages' => $projectstages, 'projecttimetableitems' => $projecttimetableitems, 'expenses' => $allexpensestype, 'incomes' => $dataincomes), 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);

}