/var/www/enzatesting.onesolution.hk/finances_individual_cus1.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
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
<?php
$formid 
"Order";
require_once 
"inc/configure.php";

$refid = (int)setDefaultReqVar('refid''');
$refidPass $refid;


if (
$refid) {
    
// Récupérez les informations du client
    
$sql_customer "SELECT * FROM dbo.master_customer WHERE refid = :refid";
    
$sth_customer $dbh->prepare($sql_customer);
    
$sth_customer->execute(array(':refid' => $refid));
    
$row_customer $sth_customer->fetch();

    if (!
$row_customer) {
        
myerror("Client non trouvé pour le RéfID : $refid");
        exit;
    }
} else {
    
myerror(INVALID WS REQUESET);
    exit;
}

// Extraire le chemin d'accès et les paramètres de requête de l'URL actuelle
$url_parts parse_url($_SERVER['REQUEST_URI']);
$path $url_parts['path'];

// Supprimer le préfixe "/Enza/" du chemin d'accès
$path_without_prefix str_replace('/Enza/'''$path);

// Ajouter le paramètre "refid" à la fin du chemin d'accès
$path_with_refid $path_without_prefix '?refid=' $refid;

$_REQUEST['vendor'] = setDefaultReqVar("vendor"$_SESSION['defaultcompany']);

search_orderField($_REQUEST['act'], $_REQUEST['customer'], $_REQUEST['launchdate_start'], $_REQUEST['launchdate_end'], $_REQUEST['deliverydate_start'], $_REQUEST['deliverydate_end'], $_REQUEST['finished'], $_REQUEST['status'], $_REQUEST['vendor']);
search_miscField($_REQUEST['act'], $_REQUEST['uom_cy']);

$currency $_REQUEST['uom_cy'];
$showUSD true;
$showCNY true;
if (
$currency == 'USD') {
    
$showCNY false;
} elseif (
$currency == 'CNY') {
    
$showUSD false;
}

// Retrieve the selected type (Invoice or Credit Note)
$dataType = isset($_REQUEST['data_type']) && ($_REQUEST['data_type'] === "CreditNote") ? "Credit Note" "Invoice";

if (isset(
$_GET['amount_toolarge']) && $_GET['amount_toolarge'] === 'true') {
    echo 
"<script>alert('The amount entered is too high. Please enter an amount lower than the remaining balance.');</script>";
    echo 
'<script>setTimeout(function(){ window.location.href = "finances_individual_cus1.php?refid=' $refidPass '"; });</script>';
}
if (isset(
$_GET['amount_null']) && $_GET['amount_null'] === 'true') {
    echo 
"<script>alert('The amount entered cannot be under or equal to 0.');</script>";
    echo 
'<script>setTimeout(function(){ window.location.href = "finances_individual_cus1.php?refid=' $refidPass '"; });</script>';
}
if (isset(
$_GET['existing_ref']) && $_GET['existing_ref'] === 'true') {
    echo 
"<script>alert('Unable to delete a deposit/payment used in a payment, check that no payment uses this deposit/payment and try again.');</script>";
    echo 
'<script>setTimeout(function(){ window.location.href = "finances_individual_cus1.php?refid=' $refidPass '"; });</script>';
}
if (isset(
$_GET['RemainingBelow0']) && $_GET['RemainingBelow0'] === 'true') {
    echo 
"<script>alert('Impossible to have a remaining amount below 0, change the new amount and try again.');</script>";
    echo 
'<script>setTimeout(function(){ window.location.href = "finances_individual_cus1.php?refid=' $refidPass '"; });</script>';
}


?>


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>ENZA</title>
    <link rel="stylesheet" type="text/css" href="css/style.css" />
    <?php require_once "inc/jsheader.php"?>
    <script lang="javascript" src="https://cdn.sheetjs.com/xlsx-0.20.0/package/dist/xlsx.full.min.js"></script>
    <?php echo '<script>var dataType = "' $dataType '";</script>'?>
    <!-- <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> -->
    <!-- <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> -->
    <!-- <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> -->
    <script>
        $(document).ready(function() {


            $("#launchdate_start").datepicker({
                dateFormat: "yy-mm-dd",
                showOn: "both",
                defaultDate: "<?= $_REQUEST['launchdate_start'?>"
            });

            $("#launchdate_end").datepicker({
                dateFormat: "yy-mm-dd",
                showOn: "both",
                defaultDate: "<?= $_REQUEST['launchdate_end'?>"
            });

            $("#deliverydate_start").datepicker({
                dateFormat: "yy-mm-dd",
                showOn: "both",
                defaultDate: "<?= $_REQUEST['deliverydate_start'?>"
            });

            $("#deliverydate_end").datepicker({
                dateFormat: "yy-mm-dd",
                showOn: "both",
                defaultDate: "<?= $_REQUEST['deliverydate_end'?>"
            });

            $("#datadate_start").datepicker({
                dateFormat: "yy-mm-dd",
                showOn: "both",
                defaultDate: "<?= $_REQUEST['datadate_start'?>"
            });

            $("#datadate_end").datepicker({
                dateFormat: "yy-mm-dd",
                showOn: "both",
                defaultDate: "<?= $_REQUEST['datadate_end'?>"
            });


            //dialog for printing selection
            $("#dialog-print").dialog({
                width: 400,
                autoOpen: false,
                modal: true,
                buttons: {
                    '<?= CANCEL ?>': function() {
                        $(this).dialog("close");
                    },
                    '<?= PRINT_ ?>': function() {
                        $("#print_form").submit();
                    }
                }
            });
            $("#print_trig").on("click", function() {
                $("#dialog-print").dialog("open");
                return false;
            });


        });
    </script>
    <style>
        .table_container {
            display: flex;
            justify-content: space-around;
            width: 100%;
        }

        .c1_bg {
            height: 100%;
            margin-right: 20px;
        }

        .c1_bg_Content {
            position: relative;
            top: 0;
        }

        /* Style pour la div qui englobe le tableau et permet le défilement */
        .scrollable-table {
            max-height: 500px;
            overflow-y: scroll;
        }

        .scrollable-tableOutStanding {
            max-height: 805px;
            overflow-y: scroll;
            display: block;
            margin-right: 20px;
        }

        /* Style pour le tableau */
        .scrollable-table table {
            width: 100%;
            border-collapse: collapse;
        }

        .scrollable-tableOutStanding table {
            width: 100%;
            border-collapse: collapse;
        }


        /* Style pour l'en-tête du tableau */
        .scrollable-table thead {
            background-color: #f0f0f0;
            /* Couleur de fond de l'en-tête, personnalisez-la selon vos préférences */
        }

        .scrollable-tableOutStanding thead {
            background-color: #f0f0f0;
            /* Couleur de fond de l'en-tête, personnalisez-la selon vos préférences */
        }

        /* Style pour les cellules de l'en-tête */
        .scrollable-table th {
            position: sticky;
            top: 0;
            background-color: #f0f0f0;
            /* Couleur de fond de l'en-tête, assortie à celle de thead */
            z-index: 2;
            /* Pour s'assurer que l'en-tête reste au-dessus du contenu lors du défilement */
        }

        .scrollable-tableOutStanding th {
            position: sticky;
            top: 0;
            background-color: #f0f0f0;
            /* Couleur de fond de l'en-tête, assortie à celle de thead */
            z-index: 2;
            /* Pour s'assurer que l'en-tête reste au-dessus du contenu lors du défilement */
        }

        .scrollable-tableOutStanding tfoot {
            position: sticky;
            bottom: 0;
            background-color: #f0f0f0;
            /* Couleur de fond de l'en-tête, assortie à celle de thead */
            z-index: 2;
            /* Pour s'assurer que l'en-tête reste au-dessus du contenu lors du défilement */
        }

        /* Style pour les cellules du corps du tableau */
        .scrollable-table td {
            /* Vos styles de cellules ici */
        }


        /* Style pour la partie fixe en haut de la page */
        #fixed-section {

            position: sticky;
            top: 0;
            z-index: 3;
        }

        .custom-link {
            color: #333;
            /* Couleur du texte du lien, par exemple, gris foncé (#333) */
            text-decoration: none;
            /* Supprime le soulignement du lien */
            font-weight: bold;
            /* Met en gras le texte du lien (facultatif) */
            text-decoration: underline;
        }


        .modifydepositformshowstyle {
            display: flex;
            text-align: center;
            max-width: 100px;
        }

        .modifydepositformshowstyle input {
            max-width: 110px;
            font-size: 12px;
        }

        .modifyfullPaymentformshowstyle {
            display: flex;
            text-align: center;
            max-width: 100px;
        }

        .modifyfullPaymentformshowstyle input {
            max-width: 110px;
            font-size: 12px;
        }

        .td-align-right {
            text-align: right;
        }

        .td-align-center {
            text-align: center;
        }

        .td-red {
            color: red;
        }

        .bg-white {
            background-color: #FFFFFF;
        }
    </style>

</head>


<body>


    <table width="100%" border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td valign="top" class="top"><?php require "mod_webhead.php"?></td>
        </tr>
        <tr>
            <td>

                <table width="100%" border="0" cellpadding="0" cellspacing="0">
                    <tr>
                        <td width="200" valign="top" class="menu_bg"><?php require "mod_menu.php"?></td>
                        <td valign="top" class="padding1">

                            <?php if (in_array($_SESSION['user'], array('jmcenza''Linda''Christine Mung''Pascal''ITDept'))) { ?>

                                <table width="100%" border="0" cellpadding="0" cellspacing="0">

                                    <tr>


                                        <table width="100%" border="0" cellpadding="0" cellspacing="0">
                                            <tr>
                                                <!-- c'est elle la colonne principale -->
                                                <td valign="top" class="padding1">

                                                    <table width="100%" border="0" cellpadding="0" cellspacing="0">
                                                        <!-- c'est elle la table 1 -->

                                                        <td class="c1_bg">

                                                            <div class="c1_bg_Content">

                                                                <form action="<?= $path_with_refid ?>" method="post">
                                                                    <table width="100%" border="0" cellpadding="0" cellspacing="0" class="search">
                                                                        <tr>
                                                                            <td width="120" valign="top"><?= BALANCE ?>
                                                                                :<br />
                                                                                <span class="stext1"><?= INDIVIDUAL ?> <?= BALANCE ?>:</span>
                                                                            </td>
                                                                            <td valign="top">

                                                                                <table>
                                                                                    <?php /*   <!-- <tr>
                                                                                                <td class=" stext2"><?= INVOICE ?>/<?= CREDIT_NOTE ?>
                                                                                    </td>
                                                                                    <td class="stext2" colspan="2">
                                                                                        <select name="data_type" id="data_type">
                                                                                            <option value="Invoice" <?= isset($_REQUEST['data_type']) && $_REQUEST['data_type'] === 'Invoice' ? 'selected' : '' ?>><?= INVOICE ?></option>
                                                                                            <option value="CreditNote" <?= isset($_REQUEST['data_type']) && $_REQUEST['data_type'] === 'CreditNote' ? 'selected' : '' ?>><?= CREDIT_NOTE ?></option>
                                                                                        </select>

                                                                                    </td>
                                                                                </tr> -->
                                                                                            <!-- <td class="stext2"><?= CUSTOMER ?></td>
                                                            <td class="stext2" colspan="2">
                                                                <select name="customer">
                                                                    <option value=""></option>
                                                                    <?= customer_option($_REQUEST['customer'], true) ?>
                                                                </select>
                                                            </td>
                                                            <td class="stext2"><?= CURRENCY ?></td>
                                                            <td class="stext2">
                                                                <select name="uom_cy">
                                                                    <option value=""></option>
                                                                    <?= master_option("UOM_CY", $_REQUEST['uom_cy'], true) ?>
                                                                </select>
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td class="stext2"><?= VENDOR ?></td>
                                                            <td class="stext2" colspan="2">
                                                                <select name="vendor">
                                                                    <option value=""></option>
                                                                    <?= vendor_option($_REQUEST['vendor'], true) ?>
                                                                </select>
                                                            </td>
                                                            <td>&nbsp;</td>
                                                            <td>&nbsp;</td>
                                                        </tr>
                                                        <tr>
                                                            <td class="stext2"><?= STATUS ?></td>
                                                            <td class="stext2" colspan="2">
                                                                <select name="status">
                                                                    <option value=""></option>
                                                                    <?= master_option("INVOICE_STATUS", $_REQUEST['status'], true) ?>
                                                                </select>
                                                            </td> 
                                                            <td>&nbsp;</td>
                                                            <td>&nbsp;</td>
                                                        </tr> --> */ 
?>
                                                                                    <tr>

                                                                                        <td class="stext2"><?= LAUNCH_DATE ?></td>
                                                                                        <td class="stext2"><input type="text" name="launchdate_start" id="launchdate_start" value="<?= $_REQUEST['launchdate_start'?>" class="shortfield" />
                                                                                        </td>
                                                                                        <td class="stext2"><input type="text" name="launchdate_end" id="launchdate_end" value="<?= $_REQUEST['launchdate_end'?>" class="shortfield" />
                                                                                        </td>
                                                                                        <td>&nbsp;</td>
                                                                                        <td>&nbsp;</td>
                                                                                        <td class="stext2"><?= DATA ?><?= WS ?><?= DATE ?></td>
                                                                                        <td class="stext2"><input type="text" name="datadate_start" id="datadate_start" value="<?= $_REQUEST['datadate_start'?>" class="shortfield" />
                                                                                        </td>
                                                                                        <td class="stext2"><input type="text" name="datadate_end" id="datadate_end" value="<?= $_REQUEST['datadate_end'?>" class="shortfield" />
                                                                                        </td>
                                                                                    </tr>
                                                                                    <tr>
                                                                                        <td class="stext2"><?= DUE ?><?= WS ?><?= DATE ?></td>
                                                                                        <td class="stext2"><input type="text" name="deliverydate_start" id="deliverydate_start" value="<?= $_REQUEST['deliverydate_start'?>" class="shortfield" />
                                                                                        </td>
                                                                                        <td class="stext2"><input type="text" name="deliverydate_end" id="deliverydate_end" value="<?= $_REQUEST['deliverydate_end'?>" class="shortfield" />
                                                                                        </td>

                                                                                    </tr>
                                                                                    <tr>
                                                                                        <td class="stext2"><?= FINISHED ?></td>
                                                                                        <td class="stext2" colspan="2">
                                                                                            <input type="checkbox" name="finished" <?= empty($_REQUEST['finished']) ? '' 'checked="checked"' ?> />
                                                                                        </td>
                                                                                        <td>&nbsp;</td>
                                                                                        <td>&nbsp;</td>
                                                                                    </tr>

                                                                                </table>
                                                                            </td>
                                                                            <td align="right" valign="top">
                                                                                <input type="image" src="image/btn_search.jpg" width="64" height="20" />&nbsp;
                                                                                &nbsp;
                                                                                <a href="<?= $path_with_refid ?>" title="<?= CLEAR ?>"><img src="image/icon_close.jpg" width="20" height="20" align="top" alt="<?= CLEAR ?>" /></a>
                                                                                <br /><br />
                                                                                <a class="uibutton" href="javascript:;" id="print_trig"><span class="ui-icon0 ui-icon-print"><?= PRINT_ ?></span></a>
                                                                                <!-- <span class="mod_menu"><a href="#" id="exportToExcel" class="uibutton"><?= EXPORT ?> <?= TO ?> <?= EXCEL ?></a></span> -->
                                                                                <a href="finances_balance.php" class="closebtn"><?= CLOSE ?></a>

                                                                            </td>


                                                                        </tr>

                                                                    </table>
                                                                </form>

                                                            </div>


                                                        </td>


                                                        <!-- c'est elle la table 2 -->

                                                        <?php
                                                        $sql_clause 
'';
                                                        
$sql_param = array();
                                                        
$sql_clause_2 '';
                                                        
$sql_param_2 = array();

                                                        
$sql_clause_ttl_ivc_amount '';
                                                        
$sql_param_ttl_ivc_amount = array();

                                                        
$sql_clause_deposit '';
                                                        
$sql_param_deposit = array();

                                                        
$sql_clause_fullPayment '';
                                                        
$sql_param_fullPayment = array();

                                                        
$sql_clause_creditNote '';
                                                        
$sql_param_creditNote = array();


                                                        if (!empty(
$_REQUEST['finished'])) {
                                                            
$sql_clause .= 'AND finished = :finished ';
                                                            
$sql_param[':finished'] = '1';
                                                            
$sql_clause_2 .= 'AND ic.finished = :finished ';
                                                            
$sql_param_2[':finished'] = '1';
                                                            
$sql_clause_ttl_ivc_amount .= 'AND finished = :finished ';
                                                            
$sql_param_ttl_ivc_amount[':finished'] = '1';

                                                            
$sql_clause_deposit .= 'AND deposit_status = :status ';
                                                            
$sql_param_deposit[':status'] = 'FINISHED';

                                                            
$sql_clause_fullPayment .= 'AND payments_status = :status ';
                                                            
$sql_param_fullPayment[':status'] = 'FINISHED';

                                                            
$sql_clause_creditNote .= 'AND finished = :finished ';
                                                            
$sql_param_creditNote[':finished'] = '1';
                                                        } else {
                                                            
$sql_clause .= 'AND (finished <> :finished OR finished IS NULL) ';
                                                            
$sql_param[':finished'] = '1';
                                                            
$sql_clause_2 .= 'AND (ic.finished <> :finished OR ic.finished IS NULL) ';
                                                            
$sql_param_2[':finished'] = '1';
                                                            
$sql_clause_ttl_ivc_amount .= 'AND (finished <> :finished OR finished IS NULL) ';
                                                            
$sql_param_ttl_ivc_amount[':finished'] = '1';

                                                            
$sql_clause_deposit .= 'AND deposit_status <> :status ';
                                                            
$sql_param_deposit[':status'] = 'FINISHED';

                                                            
$sql_clause_fullPayment .= 'AND payments_status <> :status ';
                                                            
$sql_param_fullPayment[':status'] = 'FINISHED';

                                                            
$sql_clause_creditNote .= 'AND (finished <> :finished OR finished IS NULL) ';
                                                            
$sql_param_creditNote[':finished'] = '1';
                                                        }

                                                        if (!empty(
$_REQUEST['status'])) {
                                                            
$sql_clause .= 'AND (status=:status) ';
                                                            
$sql_param[':status'] = $_REQUEST['status'];
                                                        }

                                                        if (!empty(
$_REQUEST['customer'])) {
                                                            
$sql_clause .= 'AND (ivc_customer=:ivc_customer) ';
                                                            
$sql_param[':ivc_customer'] = $_REQUEST['customer'];
                                                        }

                                                        
// if (!empty($_REQUEST['vendor'])) {
                                                        //     $sql_clause .= 'AND (vendor=:vendor) ';
                                                        //     $sql_param[':vendor'] = $_REQUEST['vendor'];
                                                        // }

                                                        
if (!empty($_REQUEST['launchdate_start'])) {
                                                            
$sql_clause .= 'AND launch_date>=:launchdate_start ';
                                                            
$sql_param[':launchdate_start'] = $_REQUEST['launchdate_start'];
                                                        }

                                                        if (!empty(
$_REQUEST['launchdate_end'])) {
                                                            
$sql_clause .= 'AND launch_date<=:launchdate_end ';
                                                            
$sql_param[':launchdate_end'] = $_REQUEST['launchdate_end'];
                                                        }

                                                        if (!empty(
$_REQUEST['deliverydate_start'])) {
                                                            
$sql_clause .= 'AND due_date>=:due_date_start ';
                                                            
$sql_param[':due_date_start'] = $_REQUEST['deliverydate_start'];
                                                        }

                                                        if (!empty(
$_REQUEST['deliverydate_end'])) {
                                                            
$sql_clause .= 'AND due_date<=:due_date_end ';
                                                            
$sql_param[':due_date_end'] = $_REQUEST['deliverydate_end'];
                                                        }

                                                        if (!empty(
$_REQUEST['datadate_start'])) {
                                                            
$sql_clause_2 .= 'AND icp.payment_date >= :paymentdateStart ';
                                                            
$sql_param_2[':paymentdateStart'] = $_REQUEST['datadate_start'];

                                                            
$sql_clause_ttl_ivc_amount .= 'AND launch_date>=:launchdate_start ';
                                                            
$sql_param_ttl_ivc_amount[':launchdate_start'] = $_REQUEST['datadate_start'];

                                                            
$sql_clause_deposit .= 'AND deposit_add_date >= :depositDateStart ';
                                                            
$sql_param_deposit[':depositDateStart'] = $_REQUEST['datadate_start'];

                                                            
$sql_clause_fullPayment .= 'AND payments_add_date >= :fullPaymentDateStart ';
                                                            
$sql_param_fullPayment[':fullPaymentDateStart'] = $_REQUEST['datadate_start'];

                                                            
$sql_clause_creditNote .= 'AND launch_date >= :cnLaunchDate_start ';
                                                            
$sql_param_creditNote[':cnLaunchDate_start'] = $_REQUEST['datadate_start'];
                                                        }

                                                        if (!empty(
$_REQUEST['datadate_end'])) {
                                                            
$sql_clause_2 .= 'AND icp.payment_date <= :paymentdateEnd ';
                                                            
$sql_param_2[':paymentdateEnd'] = $_REQUEST['datadate_end'];

                                                            
$sql_clause_ttl_ivc_amount .= 'AND launch_date<=:launchdate_end ';
                                                            
$sql_param_ttl_ivc_amount[':launchdate_end'] = $_REQUEST['datadate_end'];

                                                            
$sql_clause_deposit .= 'AND deposit_add_date <= :depositDateEnd ';
                                                            
$sql_param_deposit[':depositDateEnd'] = $_REQUEST['datadate_end'];

                                                            
$sql_clause_fullPayment .= 'AND payments_add_date <= :fullPaymentDateEnd ';
                                                            
$sql_param_fullPayment[':fullPaymentDateEnd'] = $_REQUEST['datadate_end'];

                                                            
$sql_clause_creditNote .= 'AND launch_date <= :cnLaunchDate_end ';
                                                            
$sql_param_creditNote[':cnLaunchDate_end'] = $_REQUEST['datadate_end'];
                                                        }

                                                        if (!empty(
$_REQUEST['uom_cy'])) {
                                                            
$sql_clause .= " AND (ivc_cus.uom_cy = :uom_cy) ";
                                                            
$sql_param[':uom_cy'] = $_REQUEST['uom_cy'];
                                                        }

                                                        if (
$sql_clause) {
                                                            
//$sql_clause = substr($sql_clause, 3);
                                                            //$sql_clause = preg_replace('/AND/', '', $sql_clause, 1);
                                                        
}

                                                        
// Ajoutez une clause pour exclure les factures en statut "Cancel"
                                                        
$sql_clause .= 'AND status != :status_cancel';
                                                        
$sql_param[':status_cancel'] = 'CAN';


                                                        
// Récupérez toutes les factures liées à ce client
                                                        
$sql_invoices "SELECT * 
                                                FROM ivc_cus 
                                                WHERE ivc_customer = :customer_code 
                                                AND ivc_nbr IS NOT NULL
                                                
$sql_clause
                                                ORDER BY launch_date ASC"
// Ajoutez la clause ORDER BY pour trier par date

                                                        
$sth_invoices $dbh->prepare($sql_invoices);
                                                        
$params $sql_param;
                                                        
$params[':customer_code'] = $row_customer['custcode'];

                                                        
$sth_invoices->execute($params);
                                                        
$invoices $sth_invoices->fetchAll();

                                                        
//print_r($params);
                                                        //print_r($sth_invoices);


                                                        // Récupérez le terme de paiement lié à ce client
                                                        
$sql_payment_terms "SELECT paymethod FROM master_customer WHERE custcode = :customer_code";
                                                        
$sth_payment_terms $dbh->prepare($sql_payment_terms);
                                                        
$sth_payment_terms->execute(array(':customer_code' => $row_customer['custcode']));
                                                        
$payment_term_result $sth_payment_terms->fetch();

                                                        
// Assurez-vous que le résultat est non vide avant de l'afficher
                                                        
$payment_term = !empty($payment_term_result) ? $payment_term_result['paymethod'] : '';


                                                        
// Récupérez le total des montants des factures liées à ce client
                                                        
$sql_total_invoices_amount "SELECT SUM(ttl_price) AS total_amount 
                                                    FROM ivc_cus 
                                                    WHERE ivc_customer = :customer_code 
                                                      
$sql_clause_ttl_ivc_amount
                                                      AND ivc_nbr IS NOT NULL"
;
                                                        
$sth_total_invoices_amount $dbh->prepare($sql_total_invoices_amount);

                                                        
$params $sql_param_ttl_ivc_amount;
                                                        
$params[':customer_code'] = $row_customer['custcode'];

                                                        
$sth_total_invoices_amount->execute($params);
                                                        
$total_invoices_amount_result $sth_total_invoices_amount->fetch();

                                                        
// Assurez-vous que le résultat est non vide avant de l'afficher
                                                        
$total_invoices_amount = !empty($total_invoices_amount_result) ? $total_invoices_amount_result['total_amount'] : 0;


                                                        
// Récupérez le total des montants des paiements liées à ce client -------------------------------------------------
                                                        
$sql_total_payment_amount "SELECT SUM(icp.payment_amount) AS total_amount
                                                        FROM ivc_cus_payment icp
                                                        JOIN ivc_cus ic ON icp.ivc_nbr = ic.ivc_nbr
                                                        WHERE ic.ivc_customer = :customer_code
                                                          
$sql_clause_2
                                                          AND icp.payment_type = 'Payment'
                                                        "
;
                                                        
$sth_total_payment_amount $dbh->prepare($sql_total_payment_amount);

                                                        
$params $sql_param_2;
                                                        
$params[':customer_code'] = $row_customer['custcode'];

                                                        
$sth_total_payment_amount->execute($params);
                                                        
$total_payment_amount_result $sth_total_payment_amount->fetch();

                                                        
// Assurez-vous que le résultat est non vide avant de l'afficher
                                                        
$total_payment_amount = !empty($total_payment_amount_result) ? $total_payment_amount_result['total_amount'] : 0;
                                                        
// ----------------------------------------------------------------------------------------------------------------




                                                        // Récupérez le total des montants des deposits liées à ce client -------------------------------------------------

                                                        
$sql_total_deposit_amount "SELECT SUM(icp.payment_amount) AS total_amount
                                                        FROM ivc_cus_payment icp
                                                        JOIN ivc_cus ic ON icp.ivc_nbr = ic.ivc_nbr
                                                        WHERE ic.ivc_customer = :customer_code
                                                          
$sql_clause_2
                                                          AND icp.payment_type = 'Deposit'
                                                        "
;
                                                        
$sth_total_deposit_amount $dbh->prepare($sql_total_deposit_amount);

                                                        
$params $sql_param_2;
                                                        
$params[':customer_code'] = $row_customer['custcode'];

                                                        
$sth_total_deposit_amount->execute($params);
                                                        
$total_deposit_amount_result $sth_total_deposit_amount->fetch();

                                                        
// Assurez-vous que le résultat est non vide avant de l'afficher
                                                        
$total_deposit_amount = !empty($total_deposit_amount_result) ? $total_deposit_amount_result['total_amount'] : 0;


                                                        
//-------------------------------------------------------------------------------------------------------------------








                                                        // Récupérez le total des montants des CREDIT NOTE liées à ce client -------------------------------------------------
                                                        
$sql_total_creditNote_amount "SELECT SUM(icp.payment_amount) AS total_amount
                                                        FROM ivc_cus_payment icp
                                                        JOIN ivc_cus ic ON icp.ivc_nbr = ic.ivc_nbr
                                                        WHERE ic.ivc_customer = :customer_code
                                                          
$sql_clause_2
                                                          AND icp.payment_type = 'CreditNote'
                                                        "
;
                                                        
$sth_total_creditNote_amount $dbh->prepare($sql_total_creditNote_amount);

                                                        
$params $sql_param_2;
                                                        
$params[':customer_code'] = $row_customer['custcode'];


                                                        
$sth_total_creditNote_amount->execute($params);
                                                        
$total_creditNote_amount_result $sth_total_creditNote_amount->fetch();

                                                        
// Assurez-vous que le résultat est non vide avant de l'afficher
                                                        
$total_creditNote_amount = !empty($total_creditNote_amount_result) ? $total_creditNote_amount_result['total_amount'] : 0;
                                                        
// -----------------------------------------------------------------------------------------------------------------------------------

                                                        // Récupérez le total des montants des factures liées à ce client OVERDUE AMOUNT --------------------------------------------------------------------
                                                        
$sql_total_remainingBalance_amount "SELECT SUM(COALESCE(remaining_balance, ttl_price)) AS total_amount
                                                                                            FROM ivc_cus
                                                                                            WHERE ivc_customer = :customer_code
                                                                                              AND due_date < GETDATE()
                                                                                              
$sql_clause_ttl_ivc_amount;";

                                                        
$sth_total_remainingBalance_amount $dbh->prepare($sql_total_remainingBalance_amount);

                                                        
$params $sql_param_ttl_ivc_amount;
                                                        
$params[':customer_code'] = $row_customer['custcode'];

                                                        
$sth_total_remainingBalance_amount->execute($params);
                                                        
$total_remainingBalance_amount_result $sth_total_remainingBalance_amount->fetch();

                                                        
// Assurez-vous que le résultat est non vide avant de l'afficher
                                                        
$total_remainingBalance_amount = !empty($total_remainingBalance_amount_result) ? $total_remainingBalance_amount_result['total_amount'] : 0;
                                                        
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------

                                                        // Récupérez le total des montants des factures liées à ce client OUTSTANDING AMOUNT ----------------------------------------------------------------------
                                                        
$sql_total_outstandingRemainingBalance_amount "SELECT SUM(COALESCE(remaining_balance, ttl_price)) AS total_amount 
                                                                                                        FROM ivc_cus 
                                                                                                        WHERE ivc_customer = :customer_code 
                                                                                                          
$sql_clause_ttl_ivc_amount;";

                                                        
$sth_total_outstandingRemainingBalance_amount $dbh->prepare($sql_total_outstandingRemainingBalance_amount);

                                                        
$params $sql_param_ttl_ivc_amount;
                                                        
$params[':customer_code'] = $row_customer['custcode'];

                                                        
$sth_total_outstandingRemainingBalance_amount->execute($params);
                                                        
$total_outstandingRemainingBalance_amount_result $sth_total_outstandingRemainingBalance_amount->fetch();
                                                        
$total_outstandingRemainingBalance_amount = !empty($total_outstandingRemainingBalance_amount_result) ? $total_outstandingRemainingBalance_amount_result['total_amount'] : 0;
                                                        
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------

                                                        
?>

                                                        <?php
                                                        
// Check if customer data has been retrieved from the database
                                                        
if (!empty($row_customer)) {
                                                            
// Display customer information

                                                            
echo "<table class='tablelist' border='0'";
                                                            echo 
"<tr><th>Code</th><th>Customer Name</th><th>Payment Terms</th><th>Total Invoices Amount</th><th>Total Payments Amount</th><th>Total Outstanding Balance Amount</th><th>Total Overdue Balance Amount</th><th>Total Deposit Used Amount</th><th>Total Credit Note Used Amount</th></tr>";
                                                            echo 
"<tr><td class='td-align-center'>" $row_customer['custcode'] . "</td><td class='td-align-center'>" $row_customer['custname_en'] . "</td><td class='td-align-center'>" $payment_term "</td><td class='td-align-right'>" numfs($total_invoices_amount) . "</td><td class='td-align-right'>" numfs($total_payment_amount) . "</td><td class='td-align-right'>" numfs($total_outstandingRemainingBalance_amount) . "</td><td class='td-align-right td-red'>" numfs($total_remainingBalance_amount) . "</td><td class='td-align-right'>" numfs($total_deposit_amount) . "</td><td class='td-align-right'>" numfs($total_creditNote_amount) . "</td></tr>";
                                                            
// Display additional customer information as needed
                                                            
echo "</table>";;
                                                            echo 
"<div class='table_container'>";
                                                            echo 
"<div class='table'>";
                                                            
// Check if invoices have been retrieved
                                                            
if (!empty($invoices)) {
                                                                echo 
"<h2>Invoices:</h2>";
                                                                echo 
"<table border='0' cellpadding='0' cellspacing='0' class='tablelist' style='width: 100%;'>";
                                                                echo 
"<tr><th>Launch Date</th><th>Due Date</th><th>Invoice Number</th><th>Customer Name</th><th>Total Invoice Amount</th><th>Remaining Balance</th></tr>";

                                                                foreach (
$invoices as $invoice) {
                                                                    
$dueDate strtotime($invoice['due_date']);
                                                                    
$today strtotime(date('Y-m-d'));

                                                                    echo 
"<tr>";
                                                                    echo 
"<td>" $invoice['launch_date'] . "</td>";
                                                                    echo 
"<td>" $invoice['due_date'] . "</td>";
                                                                    echo 
"<td>" $invoice['ivc_nbr'] . "</td>";
                                                                    echo 
"<td>" $row_customer['custname_en'] . "</td>"// Customer Name
                                                                    
echo "<td class='td-align-right'>" numfs($invoice['ttl_price']) . "</td>";

                                                                    
// Apply td-red style if the due date is exceeded
                                                                    
$remainingBalanceClass = ($dueDate $today) ? 'td-align-right td-red' 'td-align-right';
                                                                    echo 
"<td class='$remainingBalanceClass'>" numfs(($invoice['remaining_balance'] === null) ? $invoice['ttl_price'] : $invoice['remaining_balance']) . "</td>";

                                                                    echo 
"<td>" ucwords(strtolower($invoice['status'])) . "</td>";
                                                                    echo 
"<td><button class='toggle-button'>+</button></td>";
                                                                    echo 
"</tr>";

                                                                    
// Exécutez une requête SQL pour récupérer les paiements associés à cette facture
                                                                    
$sql_payments "SELECT * FROM ivc_cus_payment WHERE ivc_nbr = :ivc_nbr";
                                                                    
$sth_payments $dbh->prepare($sql_payments);
                                                                    
$sth_payments->execute(array(':ivc_nbr' => $invoice['ivc_nbr']));
                                                                    
$payments $sth_payments->fetchAll();

                                                                    
// Sub-table for refunds
                                                                    
echo "<tr class='refunds-row' style='display: none;'>";
                                                                    echo 
"<td colspan='6'>";
                                                                    echo 
"<table border='0' cellpadding='0' cellspacing='0' class='refunds-table tablelist' style='width: 100%;'>";
                                                                    echo 
"<tr><th>Date</th><th>Type</th><th>Reference</th><th>Amount</th></tr>";

                                                                    
// Example refund line (can be repeated for each refund)

                                                                    
if (!empty($payments)) {

                                                                        foreach (
$payments as $payment) {
                                                                            echo 
"<tr>";
                                                                            echo 
"<td>" $payment['payment_date'] . "</td>";
                                                                            echo 
"<td>" $payment['payment_type'] . "</td>";
                                                                            echo 
"<td>" $payment['reference'] . "</td>";
                                                                            echo 
"<td class='td-align-right'>" numfs($payment['payment_amount']) . "</td>"?>

                                                                            <?php if (in_array($_SESSION['user'], array('jmcenza''Linda''Christine Mung''ITDept'))) { ?>
                                                                                <td>
                                                                                    <form action="finances_delete_payment.php">
                                                                                        <input type="hidden" name="refidPass" value="<?php echo $refidPass ?>" />
                                                                                        <input type='hidden' name='paymentId' value="<?php echo $payment['refid'?>">
                                                                                        <input type="hidden" name="ivc_nb" value="<?php echo $invoice['ivc_nbr'?>" />
                                                                                        <button type='submit' onclick="confirmDelete(event)" name='submit'>Delete
                                                                                        </button>
                                                                                    </form>
                                                                                </td>
                                                                            <?php ?>

                                                                    <?php
                                                                            
echo "</tr>";
                                                                        }
                                                                    } else {
                                                                        echo 
"No payment found for this invoice.<br>";
                                                                    }


                                                                    echo 
"</table>";

                                                                    
$sql_deposit0 "SELECT * FROM cus_deposit WHERE cust_code = :customercode AND deposit_status NOT IN ('USED', 'FINISHED')";
                                                                    
$sth_deposit0 $dbh->prepare($sql_deposit0);
                                                                    
$sth_deposit0->execute(array(':customercode' => $row_customer['custcode']));
                                                                    
$deposits0 $sth_deposit0->fetchAll();

                                                                    
// Exécutez une requête SQL pour récupérer les paiements du client
                                                                    
$sql_paymentsFull0 "SELECT * FROM cus_payments WHERE cust_code = :customercode AND payments_status NOT IN ('USED', 'FINISHED')";
                                                                    
$sth_paymentsFull0 $dbh->prepare($sql_paymentsFull0);
                                                                    
$sth_paymentsFull0->execute(array(':customercode' => $row_customer['custcode']));
                                                                    
$fullPayments0 $sth_paymentsFull0->fetchAll();

                                                                    
// Exécutez une requête SQL pour récupérer les credit note du client
                                                                    
$sql_creditsNotes0 "SELECT * FROM cn_cus_main WHERE cn_customer = :customercode AND status NOT IN ('USED', 'FINISHED')";
                                                                    
$sql_creditsNotes0 $dbh->prepare($sql_creditsNotes0);
                                                                    
$sql_creditsNotes0->execute(array(':customercode' => $row_customer['custcode']));
                                                                    
$creditNotes0 $sql_creditsNotes0->fetchAll();

                                                                    
?>

                                                                    <!-- Form to add a refund -->
                                                                    <?php if (in_array($_SESSION['user'], array('jmcenza''Linda''Christine Mung''ITDept'))) { ?>
                                                                        <form class='add-refund-form' action="finances_add_payment.php" style='display: none;'>
                                                                            <input type="hidden" name="ivc_nb" value="<?php echo $invoice['ivc_nbr'?>" />
                                                                            <input type="hidden" name="refidPass" value="<?php echo $refidPass ?>" />
                                                                            <input type='hidden' name="remain_balance" value="<?php echo $invoice['remaining_balance'?>" />
                                                                            <input type="hidden" name="invoice_ttlprice" value="<?php echo $invoice['ttl_price'?>" />
                                                                            <input type='date' name='date' placeholder='Date'>
                                                                            <select name='type' onchange="toggleRefundInput(this)">
                                                                                <option value='default' selected>Select type
                                                                                    of
                                                                                    payment
                                                                                </option>
                                                                                <option value='Deposit'>Deposit</option>
                                                                                <option value='Payment'>Payment</option>
                                                                                <option value='CreditNote'>Credit Note
                                                                                </option>
                                                                            </select>
                                                                            <select name='reference_payment' style='display: none;'>
                                                                                <?php
                                                                                
// Iterate through the deposits and populate the options
                                                                                
foreach ($fullPayments0 as $fullPayment0) {
                                                                                    echo 
"<option value='" $fullPayment0['payments_reference'] . "'>" $fullPayment0['payments_reference'] . "</option>";
                                                                                }
                                                                                
?>
                                                                            </select>
                                                                            <!--                                                                        <input type='text' name='reference_payment'-->
                                                                            <!--                                                                               placeholder='Enter payment reference'-->
                                                                            <!--                                                                               style='display: none;'>-->
                                                                            <select name='reference_deposit' style='display: none;'>
                                                                                <?php
                                                                                
// Iterate through the deposits and populate the options
                                                                                
foreach ($deposits0 as $deposit) {
                                                                                    echo 
"<option value='" $deposit['deposit_reference'] . "'>" $deposit['deposit_reference'] . "</option>";
                                                                                }
                                                                                
?>
                                                                            </select>
                                                                            <select name='reference_creditNote' style='display: none;'>
                                                                                <?php
                                                                                
// Iterate through the deposits and populate the options
                                                                                
foreach ($creditNotes0 as $creditNote0) {
                                                                                    echo 
"<option value='" $creditNote0['cn_nbr'] . "'>" $creditNote0['cn_nbr'] . "</option>";
                                                                                }
                                                                                
?>
                                                                            </select>

                                                                            <input type="number" step="0.01" name='amount' placeholder='Amount'>
                                                                            <input type='submit' name="add_payment" value='Add' id="addButton">
                                                                        </form>
                                                                    <?php ?>

                                                                <?php
                                                                    
echo "</td>";
                                                                    echo 
"</tr>";
                                                                }
                                                                echo 
"</table>";
                                                            } else {
                                                                echo 
"<p>No invoices found for this customer.</p>";
                                                            }
                                                            echo 
"</div>";


                                                            echo 
"<div class='table table_container_right'>";
                                                            echo 
"<div class='sub_table_right'>";

                                                            unset(
$params);
                                                            
// Exécutez une requête SQL pour récupérer les paiements associés à cette facture
                                                            
$sql_deposit "SELECT * 
                                                        FROM cus_deposit 
                                                        WHERE cust_code = :customercode
                                                        
$sql_clause_deposit;";

                                                            
$sth_deposit $dbh->prepare($sql_deposit);

                                                            
$params $sql_param_deposit;
                                                            
$params[':customercode'] = $row_customer['custcode'];

                                                            
$sth_deposit->execute($params);
                                                            
$deposits $sth_deposit->fetchAll();

                                                            unset(
$params);

                                                            echo 
"<h2>Deposits:</h2>";
                                                            echo 
"<table border='0' cellpadding='0' cellspacing='0' class='tablelist depositTable' style='width: 100%;'>";
                                                            echo 
"<tr><th>Date</th><th>Reference</th><th>Total Deposit Amount</th><th>Remaining Balance</th><th>Statut</th></tr>";

                                                            foreach (
$deposits as $deposit) {
                                                                echo 
"<tr class='bg-white'>";
                                                                echo 
"<td>" $deposit['deposit_add_date'] . "</td>";
                                                                echo 
"<td>" $deposit['deposit_reference'] . "</td>";
                                                                echo 
"<td class='td-align-right'>" numfs($deposit['deposit_total_amount']) . "</td>";
                                                                echo 
"<td class='td-align-right'>" numfs($deposit['deposit_remaining_amount']) . "</td>";
                                                                echo 
"<td>" ucwords(strtolower($deposit['deposit_status'])) . "</td>"// Customer Name
                                                                
echo "<td>";

                                                                if (
in_array($_SESSION['user'], array('jmcenza''Linda''Christine Mung''ITDept'))) {

                                                                    echo 
"<button onclick=\"toggleEditDeposit(
                                                                                    '
{$deposit['refid']}',
                                                                                    '
{$deposit['deposit_reference']}',
                                                                                    '
{$deposit['deposit_add_date']}',
                                                                                    '
{$deposit['deposit_total_amount']}',
                                                                                    '
{$deposit['deposit_remaining_amount']}',
                                                                                    '
{$deposit['deposit_status']}'
                                                                                )\">Edit</button>"
;
                                                                }
                                                                echo 
"</td>"
                                                                
?>

                                                                <td>
                                                                    <?php if (in_array($_SESSION['user'], array('jmcenza''Linda''Christine Mung''ITDept'))) { ?>
                                                                        <form action="finances_delete_deposit.php">
                                                                            <input type="hidden" name="refidPass" value="<?php echo $refidPass ?>" />
                                                                            <input type='hidden' name='depositId' value="<?php echo $deposit['refid'?>">
                                                                            <input type='hidden' name='depositRef' value="<?php echo $deposit['deposit_reference'?>">
                                                                            <button type='submit' onclick="confirmDeleteDeposit(event)" name='submit'>Delete
                                                                            </button>
                                                                        </form>
                                                                    <?php ?>
                                                                </td>
                                                            <?php
                                                                
// Add the edit form dynamically
                                                                
echo "<tr id='editFormContainer_{$deposit['refid']}' class='modifydepositformshowstyle' style='display: none;'>";

                                                                echo 
"
                                                                            <form id='updateDepositForm_
{$deposit['refid']}' action='finances_update_deposit.php' style='display: none;'>
                                                                                <input type='hidden' name='depositId' value='
{$deposit['refid']}'>
                                                                                <input type='hidden' name='refidPass' value='
{$refidPass}'>
                                                                                <td><input type='date' name='newDepositDate' required></td>
                                                                                <td><input type='text' name='newDepositRef' required></td>
                                                                                <td><input type='number' step='0.01' name='newDepositTotalAmount' required></td>
                                                                                <td><input type='text' name='newDepositRemainingAmount' readonly></td>
                                                                                <td>
                                                                                    <select name='newDepositStatus'>
                                                                                        <option value='IN PROGRESS'>In Progress</option>
                                                                                        <option value='USED'>Used</option>
                                                                                        <option value='FINISHED'>Finished</option>
                                                                                    </select>
                                                                                </td>
                                                                                <td><button type='submit'>Submit</button></td>
                                                                                <td><button type='button' onclick=\"toggleEditDeposit('
{$deposit['refid']}')\">Cancel</button></td>
                                                                            </form>
                                                                        "
;

                                                                echo 
"</tr>";
                                                            }

                                                            
// Form to add a refund
                                                            
?>

                                                            <?php if (in_array($_SESSION['user'], array('jmcenza''Linda''Christine Mung''ITDept'))) { ?>
                                                                <form class='add-deposit-form' action="finances_add_deposit.php">
                                                                    <input type="hidden" name="custcode" value="<?php echo $row_customer['custcode'?>" />
                                                                    <input type="hidden" name="refidPass" value="<?php echo $refidPass ?>" />
                                                                    <input type='date' name='dateAddDeposit' placeholder='Date'>
                                                                    <input type='text' name='reference_deposit' placeholder='Enter deposit reference'>
                                                                    <input type="number" step="0.01" name='amount' placeholder='Amount'>
                                                                    <input type='submit' name="add_deposit" value='Add' id="addButton">
                                                                </form>
                                                            <?php ?>

                                                            <?php


                                                            
if (!empty($deposits)) {
                                                                echo 
"</table>";
                                                            } else {
                                                                echo 
"</table>";
                                                                echo 
"<p>No deposit found for this customer.</p>";
                                                            }


                                                            echo 
"</div>"// end sub div 1

                                                            
echo "<div class='sub_table_right'>"// sub div 2 - > Payments full

                                                            // Exécutez une requête SQL pour récupérer les paiements associés à cette facture
                                                            
$sql_paymentsFull "SELECT * 
                                                        FROM cus_payments 
                                                        WHERE cust_code = :customercode
                                                        
$sql_clause_fullPayment;";

                                                            
$sth_paymentsFull $dbh->prepare($sql_paymentsFull);

                                                            
$params $sql_param_fullPayment;
                                                            
$params[':customercode'] = $row_customer['custcode'];

                                                            
$sth_paymentsFull->execute($params);
                                                            
$fullPayments $sth_paymentsFull->fetchAll();

                                                            unset(
$params);

                                                            echo 
"<h2>Payments:</h2>";
                                                            echo 
"<table border='0' cellpadding='0' cellspacing='0' class='tablelist depositTable' style='width: 100%;'>";
                                                            echo 
"<tr><th>Date</th><th>Reference</th><th>Total Payment Amount</th><th>Remaining Balance</th><th>Status</th></tr>";

                                                            foreach (
$fullPayments as $fullPayment) {
                                                                echo 
"<tr>";
                                                                echo 
"<td>" $fullPayment['payments_add_date'] . "</td>";
                                                                echo 
"<td>" $fullPayment['payments_reference'] . "</td>";
                                                                echo 
"<td class='td-align-right'>" numfs($fullPayment['payments_total_amount']) . "</td>";
                                                                echo 
"<td class='td-align-right'>" numfs($fullPayment['payments_remaining_amount']) . "</td>";
                                                                echo 
"<td>" ucwords(strtolower($fullPayment['payments_status'])) . "</td>"// Customer Name
                                                                
echo "<td>";

                                                                if (
in_array($_SESSION['user'], array('jmcenza''Linda''Christine Mung''ITDept'))) {

                                                                    echo 
"<button onclick=\"toggleEditFullPayment(
                                                                                    '
{$fullPayment['refid']}',
                                                                                    '
{$fullPayment['payments_reference']}',
                                                                                    '
{$fullPayment['payments_add_date']}',
                                                                                    '
{$fullPayment['payments_total_amount']}',
                                                                                    '
{$fullPayment['payments_remaining_amount']}',
                                                                                    '
{$fullPayment['payments_status']}'
                                                                                )\">Edit</button>"
;
                                                                }
                                                                echo 
"</td>"
                                                            
?>

                                                                <td>
                                                                    <?php if (in_array($_SESSION['user'], array('jmcenza''Linda''Christine Mung''ITDept'))) { ?>
                                                                        <form action="finances_delete_fullPayment.php">
                                                                            <input type="hidden" name="refidPass" value="<?php echo $refidPass ?>" />
                                                                            <input type='hidden' name='fullPaymentId' value="<?php echo $fullPayment['refid'?>">
                                                                            <input type='hidden' name='fullPaymentRef' value="<?php echo $fullPayment['payments_reference'?>">
                                                                            <button type='submit' onclick="confirmDeleteFullPayment(event)" name='submit'>Delete
                                                                            </button>
                                                                        </form>
                                                                    <?php ?>
                                                                </td>
                                                            <?php
                                                                
// Add the edit form dynamically
                                                                
echo "<tr id='editFullPaymentFormContainer_{$fullPayment['refid']}' class='modifyfullPaymentformshowstyle' style='display: none;'>";

                                                                echo 
"
                                                                            <form id='updatefullPaymentForm_
{$fullPayment['refid']}' action='finances_update_fullPayment.php' style='display: none;'>
                                                                                <input type='hidden' name='fullPaymentId' value='
{$fullPayment['refid']}'>
                                                                                <input type='hidden' name='refidPass' value='
{$refidPass}'>
                                                                                <td><input type='date' name='newfullPaymentDate' required></td>
                                                                                <td><input type='text' name='newfullPaymentRef' required></td>
                                                                                <td><input type='number' step='0.01' name='newfullPaymentTotalAmount' required></td>
                                                                                <td><input type='text' name='newfullPaymentRemainingAmount' readonly></td>
                                                                                <td>
                                                                                    <select name='newfullPaymentStatus'>
                                                                                        <option value='IN PROGRESS'>In Progress</option>
                                                                                        <option value='USED'>Used</option>
                                                                                        <option value='FINISHED'>Finished</option>
                                                                                    </select>
                                                                                </td>
                                                                                <td><button type='submit'>Submit</button></td>
                                                                                <td><button type='button' onclick=\"toggleEditFullPayment('
{$fullPayment['refid']}')\">Cancel</button></td>
                                                                            </form>
                                                                        "
;

                                                                echo 
"</tr>";
                                                            }

                                                            
// Form to add a refund
                                                            
?>

                                                            <?php if (in_array($_SESSION['user'], array('jmcenza''Linda''Christine Mung''ITDept'))) { ?>
                                                                <form class='add-fullPayment-form' action="finances_add_fullPayment.php">
                                                                    <input type="hidden" name="custcode" value="<?php echo $row_customer['custcode'?>" />
                                                                    <input type="hidden" name="refidPass" value="<?php echo $refidPass ?>" />
                                                                    <input type='date' name='dateAddfullPayment' placeholder='Date'>
                                                                    <input type='text' name='reference_fullPayment' placeholder='Enter payment reference'>
                                                                    <input type="number" step="0.01" name='amount' placeholder='Amount'>
                                                                    <input type='submit' name="add_fullPayment" value='Add' id="addButton">
                                                                </form>
                                                            <?php ?>

                                                            <?php


                                                            
if (!empty($fullPayments)) {
                                                                echo 
"</table>";
                                                            } else {
                                                                echo 
"</table>";
                                                                echo 
"<p>No payments found for this customer.</p>";
                                                            }


                                                            echo 
"</div>"// end div 2

                                                            
echo "<div class='sub_table_right'>"// sub div 3 - credits notes

                                                            // Exécutez une requête SQL pour récupérer les paiements associés à cette facture
                                                            
$sql_creditsNotes "SELECT * 
                                                        FROM cn_cus_main 
                                                        WHERE cn_customer = :cn_customer 
                                                          
$sql_clause_creditNote;";

                                                            
$sth_creditsNotes $dbh->prepare($sql_creditsNotes);

                                                            
$params $sql_param_creditNote;
                                                            
$params[':cn_customer'] = $row_customer['custcode'];

                                                            
$sth_creditsNotes->execute($params);
                                                            
$creditsNotes $sth_creditsNotes->fetchAll();

                                                            unset(
$params);

                                                            echo 
"<h2>Credits Notes:</h2>";
                                                            echo 
"<table border='0' cellpadding='0' cellspacing='0' class='tablelist depositTable' style='width: 100%;'>";
                                                            echo 
"<tr><th>Date</th><th>Reference</th><th>Total Credit Note Amount</th><th>Remaining Amount</th><th>Status</th></tr>";


                                                            foreach (
$creditsNotes as $creditNote) {
                                                                echo 
"<tr>";
                                                                echo 
"<td>" $creditNote['launch_date'] . "</td>"// voir ce que j'affiche
                                                                
echo "<td>" $creditNote['cn_nbr'] . "</td>";
                                                                echo 
"<td class='td-align-right'>" numfs($creditNote['ttl_amt']) . "</td>";
                                                                echo 
"<td class='td-align-right'>" numfs(($creditNote['remaining_amount'] === null) ? $creditNote['ttl_amt'] : $creditNote['remaining_amount']) . "</td>";
                                                                echo 
"<td>" ucwords(strtolower($creditNote['status'])) . "</td>"// Customer Name
                                                                
echo "</td>";
                                                                echo 
"</tr>";
                                                            }
                                                            
// Form to add a refund
                                                            
?>


                                                        <?php


                                                            
if (!empty($creditsNotes)) {
                                                                echo 
"</table>";
                                                            } else {
                                                                echo 
"</table>";
                                                                echo 
"<p>No credit note found for this customer.</p>";
                                                            }

                                                            echo 
"</div>";


                                                            echo 
"</div>";
                                                        } else {
                                                            
// If no customer data was found, display an error message
                                                            
echo "<p>No data found for RefID: $refid</p>";
                                                        }


                                                        
?>


                                                    </table>


                                                </td>
                                            </tr>


                                        </table>


                                    </tr>


                                </table>

                            <?php ?>


                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>

    <div class="dialog-print" id="dialog-print" title="<?= PRINT_ ?>">
        <p>
        <form action="finances_printIndividualBalance.php" id="print_form" method="get" target="_blank">
            <select name="tid"></option><?= bal_cus_template_option() ?></select>
            <input type="hidden" name="refid" value="<?= $refid ?>" />
            <!--<input type="submit" value="<?= PRINT_ ?><?= $onprint ?> />-->
            </p>
        </form>
    </div>
    <script>
        // JavaScript for managing the display of refunds and the button text
        const toggleButtons = document.querySelectorAll('.toggle-button');
        const refundsRows = document.querySelectorAll('.refunds-row');
        const addRefundForms = document.querySelectorAll('.add-refund-form');

        toggleButtons.forEach((button, index) => {
            button.addEventListener('click', () => {
                if (refundsRows[index].style.display === 'none') {
                    refundsRows[index].style.display = 'table-row';
                    addRefundForms[index].style.display = 'block';
                    button.textContent = '-';
                } else {
                    refundsRows[index].style.display = 'none';
                    addRefundForms[index].style.display = 'none';
                    button.textContent = '+';
                }
            });
        });

        function toggleRefundInput(select) {
            const selectedValue = select.value;
            const textInput = select.nextElementSibling;
            const selectInput = textInput.nextElementSibling;
            const selectInput2 = selectInput.nextElementSibling;

            if (selectedValue === 'Deposit') {
                textInput.style.display = 'none';
                selectInput.style.display = 'inline-block';
                selectInput2.style.display = 'none';
            } else if (selectedValue === 'Payment') {
                textInput.style.display = 'inline-block';
                selectInput.style.display = 'none';
                selectInput2.style.display = 'none';
            } else if (selectedValue === 'CreditNote') {
                textInput.style.display = 'none';
                selectInput.style.display = 'none';
                selectInput2.style.display = 'inline-block';
            } else {
                textInput.style.display = 'none';
                selectInput.style.display = 'none';
                selectInput2.style.display = 'none';
            }
        }


        function confirmDelete(event) {
            if (confirm("Are you sure you want to delete this payment ?")) {
                // L'utilisateur a confirmé la suppression
                // Submit the form to delete the payment.
                document.getElementById("deletePaymentForm").submit();
            } else {
                event.preventDefault();

            }
        }

        function confirmDeleteDeposit(event) {
            if (confirm("Are you sure you want to delete this deposit ?")) {
                document.getElementById("deleteDepositForm").submit();
            } else {
                event.preventDefault();
            }
        }

        function confirmDeleteFullPayment(event) {
            if (confirm("Are you sure you want to delete this payment ?")) {
                document.getElementById("deletefullPaymentForm").submit();
            } else {
                event.preventDefault();
            }
        }


        function toggleEditDeposit(depositId, depositRef, depositDate, depositTotalAmount, depositRemainingAmount, depositStatus) {
            var formContainer = document.getElementById('editFormContainer_' + depositId);
            var form = document.getElementById('updateDepositForm_' + depositId);

            if (formContainer.style.display === 'none' || formContainer.style.display === '') {
                // Set form values based on the current deposit
                form.elements['newDepositDate'].value = depositDate;
                form.elements['newDepositRef'].value = depositRef;
                form.elements['newDepositTotalAmount'].value = depositTotalAmount;
                form.elements['newDepositRemainingAmount'].value = depositRemainingAmount;
                form.elements['newDepositStatus'].value = depositStatus;

                // Toggle form and form container visibility
                formContainer.style.display = 'table-row';
                form.style.display = 'block';
            } else {
                // If the form is already open, close it
                formContainer.style.display = 'none';
                form.style.display = 'none';
            }
        }

        function submitUpdateDeposit() {
            document.getElementById("updateDepositForm").submit();
        }


        function toggleEditFullPayment(depositId, depositRef, depositDate, depositTotalAmount, depositRemainingAmount, depositStatus) {
            var formContainer = document.getElementById('editFullPaymentFormContainer_' + depositId);
            var form = document.getElementById('updatefullPaymentForm_' + depositId);

            if (formContainer.style.display === 'none' || formContainer.style.display === '') {
                // Set form values based on the current deposit
                form.elements['newfullPaymentDate'].value = depositDate;
                form.elements['newfullPaymentRef'].value = depositRef;
                form.elements['newfullPaymentTotalAmount'].value = depositTotalAmount;
                form.elements['newfullPaymentRemainingAmount'].value = depositRemainingAmount;
                form.elements['newfullPaymentStatus'].value = depositStatus;

                // Toggle form and form container visibility
                formContainer.style.display = 'table-row';
                form.style.display = 'block';
            } else {
                // If the form is already open, close it
                formContainer.style.display = 'none';
                form.style.display = 'none';
            }
        }

        function submitUpdateFullPayment() {
            document.getElementById("updatefullPaymentForm").submit();
        }
    </script>

</body>

</html>