/var/www/onesupportdemo.onesolution.hk/inc/configure_bk.php


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
<?php
//-----------------------------------------------------------------------------
// Define
//-----------------------------------------------------------------------------
define('PROJECT_FOLDER''');
define('PROJECT_PATH''/');
define('PROJECT_ROOT'$_SERVER['DOCUMENT_ROOT'] . PROJECT_PATH);

//-----------------------------------------------------------------------------
// Error reporting level
//-----------------------------------------------------------------------------
    
error_reporting(E_ALL E_NOTICE);
    
//error_reporting(E_ALL);
    
ini_set('display_errors'1);
//-----------------------------------------------------------------------------
// Timezone
//-----------------------------------------------------------------------------
    
date_default_timezone_set('Asia/Hong_Kong');
//date_default_timezone_set('HKT/8.0/no DST');

//-----------------------------------------------------------------------------
// Session
//-----------------------------------------------------------------------------
    
if ($without_session_start !== true) {
        
session_start();
    }

//-----------------------------------------------------------------------------
// Send default header
//-----------------------------------------------------------------------------
    
if ($without_send_header !== true) {
        
// IE use last version
        
if ($without_use_last_ie_version !== true) {
            
header('X-UA-Compatible: IE=edge,chrome=1');
        }
        
// Powered by
        
if ($without_x_powered_by !== true) {
            
header('X-Powered-By: OneSolution');
        }
        
// No cache
        
if ($without_no_cache_header !== true) {
            
// Expires in the past
            
header('Expires: Mon, 26 Jul 1990 05:00:00 GMT');
            
// Always modified
            
header('Last-Modified: ' gmdate("D, d M Y H:i:s") . ' GMT');
            
// HTTP/1.1
            
header('Cache-Control: no-store, no-cache, must-revalidate');
            
header('Cache-control: private'false); // IE 6 FIX
            
header('Cache-Control: post-check=0, pre-check=0'false);
            
// HTTP/1.0
            
header('Pragma: no-cache');
        }
    }

//-----------------------------------------------------------------------------
// Connections
//-----------------------------------------------------------------------------
    
if ($without_connection !== true) {
        
$PDO_OPTIONS = array(
            
PDO::ATTR_CASE              => PDO::CASE_LOWER,
            
PDO::ATTR_ERRMODE           => PDO::ERRMODE_EXCEPTION,
            
PDO::ATTR_ORACLE_NULLS      => PDO::NULL_NATURAL,
            
PDO::ATTR_STRINGIFY_FETCHES => false,
        );

        
//-----------------------------------------------------------------------------
        // MySQL
        //-----------------------------------------------------------------------------

        // production
        
$dbh = new PDO("mysql:host=192.168.171.21;dbname=onesupport_demo"'onesupportdemo''RE34Gh#m'$PDO_OPTIONS);

        
$sql        "SET NAMES ?";
        
$parameters = array('utf8');
        if (!(
$sth $dbh->prepare($sql))) {
            throw new 
Exception("sql prepare statement failure: $sql");
        }
        
$sth->setFetchMode(PDO::FETCH_ASSOC);
        if (!
$sth->execute($parameters)) {
            throw new 
Exception("sql execute statement failure: $sql");
        }

        
//-----------------------------------------------------------------------------
        // SQL Server
        //-----------------------------------------------------------------------------
//    $sqlsrv_dbh = new PDO("sqlsrv:Server=IP;Database=oneDB", 'USER', 'PW', $PDO_OPTIONS);
    
}

//-----------------------------------------------------------------------------
// Global functions
//-----------------------------------------------------------------------------
    
require_once(__DIR__ '/class.phpmailer.php');
    function 
createPHPMailer()
    {
        
$mailer = new PHPMailer();
        
$mailer->IsSMTP();
        
$mailer->Host     "localhost";
        
$mailer->CharSet  "UTF-8";
        
$mailer->WordWrap 50;
        
$mailer->IsHTML(true);
        return 
$mailer;
    }

    function 
redirectAndExit($url)
    {
        
header('Location: ' $url);
        exit;
    }

    function 
isPost()
    {
        return 
strtoupper($_SERVER['REQUEST_METHOD']) == 'POST';
    }

    function 
isGet()
    {
        return 
strtoupper($_SERVER['REQUEST_METHOD']) == 'GET';
    }

    
/**
     * Wrapper of htmlspecialchars()
     *
     * @param string $text
     * @param string $charset
     *
     * @return string
     */
    
function h($text$charset null)
    {
//    return htmlspecialchars($text, ENT_QUOTES | ENT_HTML401, isset($charset) ? $charset : 'UTF-8');
        
return htmlspecialchars($textENT_QUOTES, isset($charset) ? $charset 'UTF-8');
    }

    
/**
     * Helper class - Util
     */
    
class Util
    
{

        public static function 
isAdmin()
        {
            return 
$_SESSION['webadmin']['role'] == 1;
        }

        public static function 
isGuest()
        {
            return 
$_SESSION['webadmin']['role'] == 4;
        }

        public static function 
date_to_string(DateTime $datetime$format 'Y-m-d')
        {
            return 
$datetime->format($format);
        }

        public static function 
time_to_string(DateTime $datetime$format 'H:i:s')
        {
            return 
$datetime->format($format);
        }

        public static function 
value_to_date_string($value$format 'Y-m-d')
        {
            
$output '';
            if (!empty(
$value)) {
                
$date   DateTime::createFromFormat('Y-m-d'$value);
                
$output $date->format($format);
            }
            return 
$output;
        }

        public static function 
value_to_time_string($value$format 'H:i')
        {
            
$output '';
            if (!empty(
$value)) {
                
$date   DateTime::createFromFormat('H:i:s'$value);
                
$output $date->format($format);
            }
            return 
$output;
        }

        
/**
         * This will give
         *
         * $a="/home/a.php";
         * $b="/home/root/b/b.php";
         * echo getRelativePath($a,$b), PHP_EOL;  // ./root/b/b.php
         * and
         *
         * $a="/home/apache/a/a.php";
         * $b="/home/root/b/b.php";
         * echo getRelativePath($a,$b), PHP_EOL; // ../../root/b/b.php
         * and
         *
         * $a="/home/root/a/a.php";
         * $b="/home/apache/htdocs/b/en/b.php";
         * echo getRelativePath($a,$b), PHP_EOL; // ../../apache/htdocs/b/en/b.php
         * and
         *
         * $a="/home/apache/htdocs/b/en/b.php";
         * $b="/home/root/a/a.php";
         * echo getRelativePath($a,$b), PHP_EOL; // ../../../../root/a/a.php
         *
         * @param type $from
         * @param type $to
         *
         * @return type
         */
        
public static function getRelativePath($from$to)
        {
            
$from    explode('/'$from);
            
$to      explode('/'$to);
            
$relPath $to;

            foreach (
$from as $depth => $dir) {
                
// find first non-matching dir
                
if ($dir === $to[$depth]) {
                    
// ignore this directory
                    
array_shift($relPath);
                } else {
                    
// get number of remaining dirs to $from
                    
$remaining count($from) - $depth;
                    if (
$remaining 1) {
                        
// add traversals up to first matching dir
                        
$padLength = (count($relPath) + $remaining 1) * -1;
                        
$relPath   array_pad($relPath$padLength'..');
                        break;
                    } else {
                        
$relPath[0] = './' $relPath[0];
                    }
                }
            }
            return 
implode('/'$relPath);
        }

        public static function 
link($filepath)
        {
            
$from $_SERVER['SCRIPT_FILENAME'];
            
$to   realpath($filepath);

            
$from str_replace('\\''/'$from);
            
$to   str_replace('\\''/'$to);

            
$link $from == $to '' Util::getRelativePath($from$to);
            if (empty(
$link) && $from == $to) {
                
$parts explode('/'$from);
                
$count count($parts);
                
$link  $parts[$count 1];
            }

            return 
$link;
        }

    }

//-----------------------------------------------------------------------------
// Pagination
//-----------------------------------------------------------------------------
    
abstract class Pagination
    
{

        private 
$number_per_page 15;
        private 
$show_near_pages 6;

        public function 
setNumberPerPage($number_per_page)
        {
            
$this->number_per_page $number_per_page;
        }

        public function 
getNumberPerPage()
        {
            return 
$this->number_per_page;
        }

        abstract protected function 
count();

        public function 
getOffset()
        {
            return (
$this->getCurrentPage() - 1) * $this->number_per_page;
        }

        public function 
getLimit()
        {
            return 
$this->number_per_page;
        }

        public function 
getCurrentPage()
        {
            return 
max(intval($_GET['page']), 1);
        }

        private function 
getQueryString($cleanPage true)
        {
            
$get $_GET;
            unset(
$get['page']);
            return 
$get;
        }

        protected function 
getPrevLink()
        {
            
$page $this->getCurrentPage() - 1;
            return 
$this->getPageLink($page);
        }

        protected function 
getNextLink()
        {
            
$page $this->getCurrentPage() + 1;
            return 
$this->getPageLink($page);
        }

        protected function 
getPageLink($page)
        {
            
$get         $this->getQueryString();
            
$get['page'] = max($page1);
            return 
'?' http_build_query($get);
        }

        public function 
pageCount()
        {
            
$count $this->count();
            
$page  $count floatval($this->number_per_page);
            if (
floor($page) < $page) {
                
$page floor($page) + 1;
            }
            return 
$page;
        }

        private 
$_cache_to_string;

        public function 
toString()
        {
            if (!empty(
$this->_cache_to_string)) {
                return 
$this->_cache_to_string;
            }

            
$pageCount   $this->pageCount();
            
$currentPage $this->getCurrentPage();
            
ob_start();
            
?>
            <div class="pagination">
                <ul>
                    <li<?= $currentPage == ' class="disabled"' '' ?>>
                        <a href="<?= $this->getPrevLink() ?>">&laquo;</a></li>
                    <?php
                        $is_dot 
false;
                        for (
$i 1$i <= max($pageCount1); $i++):
                            
$is_show $i == || $i == $pageCount || abs($currentPage $i) < $this->show_near_pages;
                            if (
$is_show):
                                
$is_dot true;
                                
?>
                                <li<?= $currentPage == $i ' class="active"' '' ?>>
                                    <a href="<?= $this->getPageLink($i?>"><?= $i ?></a></li>
                            <?php
                            
elseif ($is_dot):
                                
$is_dot false;
                                
?>
                                <li class="disabled"><a href="javascript:void(0)">...</a></li>
                            <?php
                            
endif;
                        endfor;
                    
?>
                    <li<?= $currentPage >= $pageCount ' class="disabled"' '' ?>>
                        <a href="<?= $this->getNextLink() ?>">&raquo;</a></li>
                </ul>
            </div>
            <?php
            $this
->_cache_to_string ob_get_contents();
            
ob_end_clean();

            return 
$this->_cache_to_string;
        }

    }

    class 
MySqlPagination extends Pagination
    
{
        private 
$sql;
        private 
$parameters;
        private 
$dbh;

        function 
__construct($sql$parameters)
        {
            global 
$dbh;

            
$this->sql        $sql;
            
$this->parameters $parameters;
            
$this->dbh        $dbh;
        }

        protected function 
count()
        {
            
$sql $this->sql;
            
$sql "SELECT COUNT(*) AS count FROM ( $sql ) t";
            if (!(
$sth $this->dbh->prepare($sql))) {
                throw new 
Exception("sql prepare statement failure: $sql");
            }
            
$sth->setFetchMode(PDO::FETCH_ASSOC);
            if (!
$sth->execute($this->parameters)) {
                throw new 
Exception("sql execute statement failure: $sql");
            }
            
$record $sth->fetch(PDO::FETCH_ASSOC);

            return 
$record['count'];
        }

        public function 
getSqlLimitAndOffset()
        {
            
$limit  $this->getLimit();
            
$offset $this->getOffset();
            return 
" LIMIT $limit OFFSET $offset ";
        }
    }

    class 
SqlsrvPagination extends Pagination
    
{
        private 
$sql;
        private 
$parameters;
        private 
$dbh;

        function 
__construct($sql$parameters)
        {
            global 
$sqlsrv_dbh;

            
$this->sql        $sql;
            
$this->parameters $parameters;
            
$this->dbh        $sqlsrv_dbh;
        }

        protected function 
count()
        {
            
$sql $this->sql;
            
$pos strpos($sql"ORDER BY");
            if (
$pos !== false) {
                
$sql substr($sql0$pos);
            }
            
$sql "SELECT COUNT(*) AS count FROM ( $sql ) t";
            if (!(
$sth $this->dbh->prepare($sql))) {
                throw new 
Exception("sql prepare statement failure: $sql");
            }
            
$sth->setFetchMode(PDO::FETCH_ASSOC);
            if (!
$sth->execute($this->parameters)) {
                throw new 
Exception("sql execute statement failure: $sql");
            }
            
$record $sth->fetch(PDO::FETCH_ASSOC);

            return 
$record['count'];
        }

        public function 
getSql()
        {
            
$sql    $this->sql;
            
$limit  $this->getLimit();
            
$offset $this->getOffset();

            
$limit  intval($limit);
            
$offset intval($offset);

            if (
$offset == 0)
                return 
preg_replace('/^SELECT\s/i''SELECT TOP ' $limit ' '$sql);

            
$orderby stristr($sql'ORDER BY');
            
$over    $orderby preg_replace('/\"[^,]*\".\"([^,]*)\"/i''"inner_tbl"."$1"'$orderby) : 'ORDER BY (SELECT 0)';

            
// Remove ORDER BY clause from $sql
            
$sql preg_replace('/\s+ORDER BY(.*)/'''$sql);

            
// Add ORDER BY clause as an argument for ROW_NUMBER()
            
$sql "SELECT ROW_NUMBER() OVER ($over) AS \"AR_ROWNUM\", * FROM ($sql) AS inner_tbl";

            
$start $offset 1;
            
$end   $offset $limit;
            return 
"WITH outer_tbl AS ($sql) SELECT * FROM outer_tbl WHERE \"AR_ROWNUM\" BETWEEN $start AND $end";
        }
    }

//-----------------------------------------------------------------------------
// Sign in
//-----------------------------------------------------------------------------
    
class SigninController
    
{

        public function 
isLogin()
        {
            return isset(
$_SESSION['webadmin']['id']) && strlen($_SESSION['webadmin']['id']);
        }

        protected function 
redirectMain()
        {
            if (
$_SESSION['webadmin']["role"] == 1) { //admin
                
redirectAndExit(Util::link(__DIR__ '/../contract/contract_alert.php'));
            } else {
                
redirectAndExit(Util::link(__DIR__ '/../main.php') . '?' http_build_query($_GET));
            }

        }

        protected function 
redirectLogin()
        {
            
redirectAndExit(Util::link(__DIR__ '/../login.php') . '?' http_build_query($_GET));
        }

        public function 
checkLogin()
        {
            if (!
$this->isLogin()) {
                
$this->redirectLogin();
            }
        }

        public function 
login()
        {
            global 
$dbh;

            if (
$this->isLogin()) {
                
$this->redirectMain();
            }

            
$message null;
            if (!empty(
$_GET['message'])) {
                
$message $_GET['message'];
            }
            
$message_heading 'Error!';
            if (!empty(
$_GET['message_heading'])) {
                
$message_heading $_GET['message_heading'];
            }
            
$message_css_class 'alert-error';
            if (!empty(
$_GET['message_css_class'])) {
                
$message_css_class $_GET['message_css_class'];
            }

            if (
isPost()) {
                
$name     $_POST['name'];
                
$password $_POST['password'];
                
$sql      "SELECT * FROM sys_login WHERE loginname = ? AND loginpw = ? AND actived = ? AND deleted = ?";
                if (!(
$sth $dbh->prepare($sql))) {
                    throw new 
Exception("sql prepare statement failure: $sql");
                }
                
$sth->setFetchMode(PDO::FETCH_ASSOC);
                if (!
$sth->execute(array($namemd5($password), 10))) {
                    throw new 
Exception("sql execute statement failure: $sql");
                }
                
$staff $sth->fetch(PDO::FETCH_ASSOC);
                if (!empty(
$staff)) {
                    
// Assign webadmin session
                    
$_SESSION['webadmin'] = $staff;

                    
// Redirect to job
                    
$this->redirectMain();
                }
                
$message           'User name or password not correct.';
                
$message_heading   'Error!';
                
$message_css_class 'alert-error';
            }

            return array(
                
'message'           => $message,
                
'message_heading'   => $message_heading,
                
'message_css_class' => $message_css_class,
            );
        }

        public function 
logout()
        {
            
// Clear webadmin session
            
unset($_SESSION['webadmin']);

            
// Redirect to login
            
$this->redirectLogin();
        }

    }

//-----------------------------------------------------------------------------
// Static values
//-----------------------------------------------------------------------------
    
class Staff
    
{

        public static function 
roleOptions()
        {
            return array(
                
=> 'Admin',
                
=> 'Engine',
                
=> 'Support',
                
=> 'Guest',
            );
        }

        public static function 
staff_name($staff_id)
        {
            global 
$dbh;

            
$sql "SELECT * from sys_login where id = ?";

            if (!(
$sth $dbh->prepare($sql))) {
                throw new 
Exception("sql prepare statement failure: $sql");
            }
            
$sth->setFetchMode(PDO::FETCH_ASSOC);
            
$parameters = array((int)$staff_id);
            if (!
$sth->execute($parameters)) {
                throw new 
Exception("sql execute statement failure: $sql");
            }
            
$staff_detail $sth->fetchAll();

            return 
$staff_detail;
        }

    }

    class 
JobDetail
    
{
        public static function 
statusOptions()
        {
            return array(
                
=> 'Open',
                
=> 'Completed',
                
=> 'Follow up',
                
=> 'Cancel',
            );
        }

        public static function 
statusOptions2($statusnum)
        {
            if (
$statusnum == 1)
                return 
'Open';
            if (
$statusnum == 2)
                return 
'Completed';
            if (
$statusnum == 3)
                return 
'Follow up';
            if (
$statusnum == 4)
                return 
'Cancel';
        }
    }

    class 
JobPending
    
{
        public static function 
convert_to_job_detail($job_pending, array $job_detail_attributes)
        {
            
$attributes array_merge($job_detail_attributes, array(
                
'from_job_pending_id' => $job_pending['id'],
            ));
            
// copy fields
            
$copy_fields = array('title''remarks');
            foreach (
$copy_fields as $field) {
                
$attributes[$field] = $job_pending[$field];
            }
            return 
$attributes;
        }
    }

    class 
Job
    
{

        public static function 
week()
        {
            return array(
                
=> 'Mon',
                
=> 'Tue',
                
=> 'Wed',
                
=> 'Thu',
                
=> 'Fri',
                
=> 'Sat',
                
=> 'Sun',
            );
        }

        public static function 
statusOptions()
        {
            return array(
                
=> 'Open',
                
=> 'Close',
                
=> 'Void',
            );
        }

        public static function 
activeperiod()
        {
            return array(
                
=> 'Daily',
                
=> 'Weekly',
                
=> 'Monthly',
            );
        }

        public static function 
whichweek()
        {
            return array(
                
=> 'The First Week of Month (1-7)',
                
=> 'The Second Week of Month (8-14)',
                
=> 'The Third Week of Month (15-21)',
                
=> 'The Fourth Week of Month (22-28)',
                
=> 'The Fifth Week of Month (29-31)',
            );
        }

        public static function 
monthly_task_option($customer_id)
        {
            global 
$dbh;

            
$sql        "SELECT * from sup_monthly_task where customer_id = '" . (int)$customer_id "'";
            
$parameters = array();
            if (!(
$sth $dbh->prepare($sql))) {
                throw new 
Exception("sql prepare statement failure: $sql");
            }
            
$sth->setFetchMode(PDO::FETCH_ASSOC);
            if (!
$sth->execute($parameters)) {
                throw new 
Exception("sql execute statement failure: $sql");
            }
            
$monthly_tasks $sth->fetchAll();

            return 
$monthly_tasks;
        }

        public static function 
typeOptions()
        {
            return array(
                
=> 'Schedule Visit',
                
=> 'Service Call',
                
=> 'Urgent Call',
                
=> 'Remote Service Call',
            );
        }

        public static function 
typeOptions2($typenum)
        {
            if (
$typenum == 1)
                return 
'Schedule Visit';
            if (
$typenum == 2)
                return 
'Service Call';
            if (
$typenum == 3)
                return 
'Urgent Call';
            if (
$typenum == 4)
                return 
'Remote Service Call';

        }

        public static function 
createDetails($keyValues)
        {
            global 
$dbh;

            if (empty(
$keyValues)) {
                
$keyValues = array();
            }

            
$sql        "SELECT column_name FROM information_schema.columns WHERE table_schema = (SELECT DATABASE()) AND table_name = ?";
            
$parameters = array('sup_job_detail');
            if (!(
$sth $dbh->prepare($sql))) {
                throw new 
Exception("sql prepare statement failure: $sql");
            }
            
$sth->setFetchMode(PDO::FETCH_ASSOC);
            if (!
$sth->execute($parameters)) {
                throw new 
Exception("sql execute statement failure: $sql");
            }
            
$job_detail_columns $sth->fetchAll();

            
$job_pending_ids    = array();
            
$job_pending_values = array();
            
//var_dump($keyValues);
            
foreach ($keyValues as $id => $attributes) {
                if (isset(
$_SESSION["all_job_ids"]) && !empty($_SESSION["all_job_ids"])) {
                    foreach (
$_SESSION["all_job_ids"] as $job_id) {
                        
$job_detail = array(
                            
'job_id' => $job_id,
                        );

                        foreach (
$job_detail_columns as $column) {
                            
$column $column['column_name'];
                            if (isset(
$attributes[$column])) {
                                
$job_detail[$column] = $attributes[$column];
                            }
                        }

                        
// Append record time
                        
$now        date("Y-m-d H:i:s");
                        
$job_detail array_merge($job_detail, array(
                            
'createdate' => $now,
                            
'createby'   => $_SESSION['webadmin']['id'],
                            
'lastupdate' => $now,
                            
'lastupby'   => $_SESSION['webadmin']['id'],
                            
'actived'    => 1,
                            
'deleted'    => 0,
                            
'status'     => 1// Open
                        
));

                        
$columns    = array();
                        
$values     = array();
                        
$parameters = array();
                        foreach (
$job_detail as $column => $value) {
                            
$columns[]    = $column;
                            
$parameters[] = !strlen($value) ? null $value;
                            
$values[]     = '?';
                        }
                        
$sql "INSERT sup_job_detail (" implode(', '$columns) . ") VALUES (" implode(', '$values) . ")";
                        if (!(
$sth $dbh->prepare($sql))) {
                            throw new 
Exception("sql prepare statement failure: $sql");
                        }
                        
$sth->setFetchMode(PDO::FETCH_ASSOC);
                        if (!
$sth->execute($parameters)) {
                            throw new 
Exception("sql execute statement failure: $sql");
                        }

                        if (!empty(
$job_detail['from_job_pending_id'])) {
                            
$job_pending_ids[]    = $job_detail['from_job_pending_id'];
                            
$job_pending_values[] = '?';
                        }
                    }
                } else {
                    
/*foreach($_SESSION["all_job_ids"] as $job_id){
                    $job_detail = array(
                        'job_id' => $job_id,
                        'actived' => 1,
                        'deleted' => 0,
                        'status' => 1, // Open
                    );*/
                    
foreach ($job_detail_columns as $column) {
                        
$column $column['column_name'];
                        if (isset(
$attributes[$column])) {
                            
$job_detail[$column] = $attributes[$column];
                        }
                    }

                    
// Append record time
                    
$now        date("Y-m-d H:i:s");
                    
$job_detail array_merge($job_detail, array(
                        
'createdate' => $now,
                        
'createby'   => $_SESSION['webadmin']['id'],
                        
'lastupdate' => $now,
                        
'lastupby'   => $_SESSION['webadmin']['id'],
                        
'actived'    => 1,
                        
'deleted'    => 0,
                        
'status'     => 1// Open
                    
));

                    
$columns    = array();
                    
$values     = array();
                    
$parameters = array();
                    foreach (
$job_detail as $column => $value) {
                        
$columns[]    = $column;
                        
$parameters[] = !strlen($value) ? null $value;
                        
$values[]     = '?';
                    }
                    
$sql "INSERT sup_job_detail (" implode(', '$columns) . ") VALUES (" implode(', '$values) . ")";
                    if (!(
$sth $dbh->prepare($sql))) {
                        throw new 
Exception("sql prepare statement failure: $sql");
                    }
                    
$sth->setFetchMode(PDO::FETCH_ASSOC);
                    if (!
$sth->execute($parameters)) {
                        throw new 
Exception("sql execute statement failure: $sql");
                    }

                    if (!empty(
$job_detail['from_job_pending_id'])) {
                        
$job_pending_ids[]    = $job_detail['from_job_pending_id'];
                        
$job_pending_values[] = '?';
                    }
                }


            }
            
/*if (!empty($job_pending_ids)) {
                $job_pending = array(
                    'actived' => 0,
                );

                // Append record time
                $now = date("Y-m-d H:i:s");
                $job_pending = array_merge($job_pending, array(
                    'lastupdate' => $now,
                    'lastupby' => $_SESSION['webadmin']['id'],
                ));

                // Update job detail
                $values = array();
                $parameters = array();
                foreach ($job_pending as $column => $value) {
                    if ($column != 'id') {
                        $parameters[] = !strlen($value) ? null : $value;
                        $values[] = "`$column` = ?";
                    }
                }

                $sql = "UPDATE sup_job_pending SET " . implode(', ', $values) . " WHERE id IN (" . implode(', ', $job_pending_values) . ")";
                $parameters = array_merge($parameters, $job_pending_ids);
                if (!($sth = $dbh->prepare($sql))) {
                    throw new Exception("sql prepare statement failure: $sql");
                }
                $sth->setFetchMode(PDO::FETCH_ASSOC);
                if (!$sth->execute($parameters)) {
                    throw new Exception("sql execute statement failure: $sql");
                }
            }*/
        
}

        public static function 
updateDetails($keyValues, array $job_details)
        {
            global 
$dbh;

            if (empty(
$keyValues)) {
                
$keyValues = array();
            }

            
$sql        "SELECT column_name FROM information_schema.columns WHERE table_schema = (SELECT DATABASE()) AND table_name = ?";
            
$parameters = array('sup_job_detail');
            if (!(
$sth $dbh->prepare($sql))) {
                throw new 
Exception("sql prepare statement failure: $sql");
            }
            
$sth->setFetchMode(PDO::FETCH_ASSOC);
            if (!
$sth->execute($parameters)) {
                throw new 
Exception("sql execute statement failure: $sql");
            }
            
$job_detail_columns $sth->fetchAll();

            
$job_detail_map = array();
            foreach (
$job_details as $job_detail) {
                
$job_detail_id                  $job_detail['id'];
                
$job_detail_map[$job_detail_id] = $job_detail;
            }

            foreach (
$keyValues as $id => $attributes) {
                
$job_detail $job_detail_map[$id];
                if (empty(
$job_detail)) {
                    throw new 
Exception('Job detail not found!');
                }

                foreach (
$job_detail_columns as $column) {
                    
$column $column['column_name'];
                    if (isset(
$attributes[$column])) {
                        
$job_detail[$column] = $attributes[$column];
                    }
                }

                
// Append record time
                
$now        date("Y-m-d H:i:s");
                
$job_detail array_merge($job_detail, array(
                    
'lastupdate' => $now,
                    
'lastupby'   => $_SESSION['webadmin']['id'],
                ));

                
$values     = array();
                
$parameters = array();
                foreach (
$job_detail as $column => $value) {
                    if (
$column != 'id') {
                        
$parameters[] = !strlen($value) ? null $value;
                        
$values[]     = "`$column` = ?";
                    }
                }
                
$sql          "UPDATE sup_job_detail SET " implode(', '$values) . " WHERE id = ?";
                
$parameters[] = $job_detail['id'];
                if (!(
$sth $dbh->prepare($sql))) {
                    throw new 
Exception("sql prepare statement failure: $sql");
                }
                
$sth->setFetchMode(PDO::FETCH_ASSOC);
                if (!
$sth->execute($parameters)) {
                    throw new 
Exception("sql execute statement failure: $sql");
                }
            }
        }

        public static function 
allow_change_status_to_confirm($id)
        {
            global 
$dbh;

            
$is_allow true;

            
$sql        "SELECT * FROM sup_job_detail WHERE job_id = ?";
            
$parameters = array($id);
            if (!(
$sth $dbh->prepare($sql))) {
                throw new 
Exception("sql prepare statement failure: $sql");
            }
            
$sth->setFetchMode(PDO::FETCH_ASSOC);
            if (!
$sth->execute($parameters)) {
                throw new 
Exception("sql execute statement failure: $sql");
            }
            
$job_details $sth->fetchAll();

            
// check any detail status is open
            
foreach ($job_details as $job_detail) {
                if (
$job_detail['status'] == 1) {
                    
$is_allow false;
                    break;
                }
            }

            return 
$is_allow;
        }

    }


//contract
    
class Contract
    
{
        public static function 
statusOptions($data NULL)
        {
            if (empty(
$data)) {
                return array(
                    
=> 'Open',
                    
=> 'Close',
                    
=> 'Void',
                    
=> 'Expired'
                
);
            } else {
                if (
$data == 1)
                    return 
'Open';
                if (
$data == 2)
                    return 
'Close';
                if (
$data == 3)
                    return 
'Void';
                if (
$data == 4)
                    return 
'Expired';
            }
        }

        public static function 
typeOptions($data NULL)
        {
            if (empty(
$data)) {
                return array(
                    
=> 'Schedule Visit',
                    
=> 'Service Call',
                    
=> 'Urgent Call',
                    
=> 'Remote Service Call',
                );
            } else {
                if (
$data == 1)
                    return 
'Schedule Visit';
                if (
$data == 2)
                    return 
'Service Call';
                if (
$data == 3)
                    return 
'Urgent Call';
                if (
$data == 4)
                    return 
'Remote Service Call';
            }
        }
    }

//Project
    
class Project
    
{
        public static function 
statusOptions()
        {
            return array(
                
=> 'Open',
                
=> 'Close',
                
//3 => 'Void',
            
);
        }

        public static function 
statusOptions2($status)
        {
            if (
$status == 1)
                return 
'Open';
            if (
$status == 2)
                return 
'Close';
            
//if($status == 3)
            //return 'Void';
        
}


    }

//Project
    
class Customer
    
{

        public static function 
company_name($customer_id)
        {
            global 
$dbh;

            
$sql "SELECT * from v_cm_customer_support where cust_id = ?";

            if (!(
$sth $dbh->prepare($sql))) {
                throw new 
Exception("sql prepare statement failure: $sql");
            }
            
$sth->setFetchMode(PDO::FETCH_ASSOC);
            
$parameters = array($customer_id);
            if (!
$sth->execute($parameters)) {
                throw new 
Exception("sql execute statement failure: $sql");
            }
            
$customer_detail $sth->fetchAll();

            return 
$customer_detail;
        }

    }


    class 
monthly_task_statusOption
    
{
        public static function 
statusOptions()
        {
            return array(
                
=> 'Open',
                
=> 'Completed',
                
=> 'Cancel',
            );
        }
    }

    class 
period_task_statusOption
    
{
        public static function 
statusOptions()
        {
            return array(
                
=> 'Open',
                
=> 'Completed',
                
=> 'Cancel',
            );
        }
    }


    if (!
function_exists('contract_type')) {
        function 
contract_type($value)
        {
            if (
$value == "1")
                return 
"Monthly";
            else if (
$value == "2")
                return 
"Package";
            else
                return 
"Error";
        }
    }

    function 
get_month_name($month)
    {
        
$months = array(
            
1  => 'Jan',
            
2  => 'Feb',
            
3  => 'Mar',
            
4  => 'Apr',
            
5  => 'May',
            
6  => 'Jun',
            
7  => 'Jul',
            
8  => 'Aug',
            
9  => 'Sep',
            
10 => 'Oct',
            
11 => 'Nov',
            
12 => 'Dec'
        
);

        return 
$months[$month];
    }


    function 
dateRange($first$last$step '+1 month'$format 'Y-m')
    {
        
$dates   = array();
        
$current strtotime($first);
        
$last    strtotime($last);

        while (
$current <= $last) {
            
$dates[] = date($format$current);
            
$current strtotime($step$current);
        }
        return 
$dates;
    }