<?php include("../Header/Session.php"); ?>
<?php include("../Header/Connection.php"); ?>

<!DOCTYPE html>
<html lang="en">
<?php include ("../Header/head.php"); ?>
<body class="skin-default fixed-layout">

<!-- Main wrapper - style you can find in pages.scss -->
<div id="main-wrapper">    
<?php include ("../Header/header.php"); ?>
<?php include ("../Header/left_menu.php"); ?>
<?php include ("../Header/right_sidebar.php"); ?>
        
<!-- Page wrapper  -->
<div class="page-wrapper">
<!-- Container fluid  -->
<div class="container-fluid">
<!-- Bread crumb and right sidebar toggle -->
<!--?php include ("../Header/breadcumb.php"); ?-->
<br><br>
<!-- End Bread crumb and right sidebar toggle -->
<!-- Start Page Content -->
<!-- ============================================================== -->

<?php
$package_owner = $_GET['package'];

if ($package_owner == "agent")
{
    $title = 'MY PACKAGE';
}
else
if ($package_owner == "customer")
{
    $title = 'MY CUSTOMER PACKAGE';
}
?>


<?php 
if ($level == '1')
{
?>
    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-body">
                    <form method="post" action="" enctype="multipart/form-data">
                        <div class="form-body">
                            <h3 class="card-title">Date Selection</h3>
                            <hr>
                            <div class="row p-t-20">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="control-label">From</label>
                                        <input type="date" class="form-control" name="from_date"  required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="control-label">To</label>
                                        <input type="date" class="form-control" name="to_date"  required>
                                    </div>
                                </div>                   
                            </div>
                        </div>
                        <div class="form-actions">
                            <button name="Date_Selection" class="btn btn-success"><i class="fa fa-check"></i> Submit</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
<?php
}
?>

<?php
if (isset($_POST['Date_Selection'])) 
{
    $from_date = $_POST['from_date'];
    $to_date = $_POST['to_date'];

    $from_date_display = date('d-m-Y', strtotime($_POST['from_date']));
    $to_date_display = date('d-m-Y', strtotime($_POST['to_date']));
}

date_default_timezone_set("Asia/Kuala_Lumpur");
$default_from_date = date('Y-m-01');
$default_to_date   = date('Y-m-t');

if (isset($_POST['Date_Selection'])) {
    $from_date = $_POST['from_date'];
    $to_date   = $_POST['to_date'];

    $from_date_display = date('d-m-Y', strtotime($from_date));
    $to_date_display   = date('d-m-Y', strtotime($to_date));
} else {
    $from_date = $default_from_date;
    $to_date   = $default_to_date;

    $from_date_display = date('d-m-Y', strtotime($from_date));
    $to_date_display   = date('d-m-Y', strtotime($to_date));
}
?>

<div class="row">
<div class="col-12">
<div class="card">
    <div class="card-body">
        <?php 
        if ($level == '1')
        {
        ?>
            <h4 class="card-title">Members Package From <?php echo $from_date_display; ?> To <?php echo $to_date_display; ?></h4>
        <?php
        }
        else
        {
        ?>
            <h4 class="card-title"><?php echo $title; ?></h4>
        <?php
        }
        ?>
        <div class="table-responsive m-t-40">            
            <table id="example23" class="display nowrap table table-hover table-striped table-bordered" cellspacing="0" width="100%">
                <thead>
                    <tr>
                        <th>Package ID</th>
                        <th>Order ID</th>
                        <th>Member Info</th>
                        <th>Package Name</th>
                        <th>Package Total Price</th>
                        <th>Package Paid Price</th>
                        <th>Package Balance Price</th>
                        <th>Purchase Date</th>
                        <th>Umrah Date</th>
                        <th>Action</th>
                    </tr>
                </thead>                                      
                <tbody>
                    <?php
                    if ($level == '1')
                    {
                        $q = "SELECT *
                        FROM woocommerce_order_info
                        Where status = '1'
                        AND DATE(created_date) BETWEEN '$from_date' AND '$to_date'
                        order by id Desc";
					}
                    else
                    if ($level == '2' && $package_owner == "agent")
                    {
                        $q = "SELECT *
                        FROM woocommerce_order_info
                        Where new_ref_code = '$ref_code'
                        And status = '1'
                        AND DATE(created_date) BETWEEN '$from_date' AND '$to_date'
                        order by id Desc";
					}
                    else
                    if ($level == '2' && $package_owner == "customer")
                    {
                        $q = "SELECT *
                        FROM woocommerce_order_info
                        Where order_comm_ref_code = '$ref_code'
                        And status = '1'
                        AND DATE(created_date) BETWEEN '$from_date' AND '$to_date'
                        order by id Desc";
					}
                    else
                    if ($level == '3')
                    {
                        $q = "SELECT *
                        FROM woocommerce_order_info
                        Where new_ref_code = '$ref_code'
                        And status = '1'
                        AND DATE(created_date) BETWEEN '$from_date' AND '$to_date'
                        order by id Desc";
					}

                    $result = $mysqli->query($q);
                    if ($result->num_rows > 0)
                    {
                        while($record = $result -> fetch_assoc())
                        {  
						    $id = $record['id'];
                            $order_id  = $record['order_id'];
                            $trans_code  = $record['trans_code'];
                            $new_ref_code  = $record['new_ref_code'];
                            $order_items  = $record['order_items'];
                            $order_full_total  = $record['order_full_total'];
                            $order_total  = $record['order_total'];
                            $paid_date = date('d-m-Y H:i:s', strtotime($record['paid_date']));
                            $created_date = date('d-m-Y H:i:s', strtotime($record['created_date']));

                            $umrah_date_raw = $record['umrah_date'] ?? '';
                            $umrah_date_display = '';

                            if (!empty($umrah_date_raw) && $umrah_date_raw != '0000-00-00' && $umrah_date_raw != '0000-00-00 00:00:00') {
                                $umrah_date_display = date('d-m-Y', strtotime($umrah_date_raw));
                            } else {
                                $umrah_date_display = '-';
                            }

                            $sql_order_item = "SELECT *
									           FROM woocommerce_order_info_item
									           Where order_id  = '$order_id'
									           And status='1'";
						    $result_order_item = $mysqli-> query($sql_order_item);
						    if ($result_order_item -> num_rows > 0)
						    {
							    $row_order_item = $result_order_item ->fetch_assoc();
							    $order_item_sku = $row_order_item['item_nilai_mata'];
						    }

                            $data_total_payment = 
                            "SELECT SUM(amount) As num 
                            FROM package_payment
                            WHERE order_id = '$order_id'
                            AND trans_code = '$trans_code'
                            AND ref_code = '$new_ref_code'
                            AND status = '1'";    
                            $result_total_payment = $mysqli->query($data_total_payment);
                            if ($result_total_payment ->num_rows > 0)
                            {
	                            $row_total_payment = $result_total_payment ->fetch_assoc();
	                            $full_total_payment = $row_total_payment['num'];
                            }

                            $order_balance = $order_full_total - $full_total_payment;

                            $sql_user = "SELECT * 
                            FROM user 
                            WHERE ref_code='$new_ref_code'
                            And status='1'";
                            $result_user = $mysqli->query($sql_user);
	                        if ($result_user ->num_rows > 0)
	                        {
		                        $row_user = $result_user ->fetch_assoc();
		                        $type_of_user = $row_user['type_of_user'];
                                $name = $row_user['name'];
                                $nick_name = $row_user['nick_name'];
                                $last_name = $row_user['last_name'];
                                $email = $row_user['email'];
                                $phone_number = $row_user['phone_number'];
	                        }  
                    ?>
                    <form method="post" action="../Controller/Database_sql.php" onsubmit="return confirm('Do you want to proceed?');" enctype="multipart/form-data">
                    <tr>
                        <td>PCK<?php echo $id; ?></td>
                        <td><?php echo $order_id; ?></td>
                        <td><?php echo $nick_name;?><br><?php echo $new_ref_code;?><br><?php echo $name;?></td>
                        <td>
                        <?php
                          $text = trim($order_items ?? '');

                          // Split by "|" into parts
                          $parts = preg_split('/\s*\|\s*/', $text);

                          $lines = [];

                          if (!empty($parts[0])) {
                              // Split first part on " - " (only once)
                              $first = $parts[0];
                              $dashParts = preg_split('/\s*-\s*/', $first, 2);

                              $lines[] = trim($dashParts[0]);          // Package name
                              if (!empty($dashParts[1])) {
                                  $lines[] = trim($dashParts[1]);      // Deposit RM ...
                              }
                          }

                          // Add remaining "|" parts (e.g., Free shipping)
                          for ($i = 1; $i < count($parts); $i++) {
                              if (trim($parts[$i]) !== '') $lines[] = trim($parts[$i]);
                          }

                          // Output as HTML with line breaks (safe)
                          echo nl2br(htmlspecialchars(implode("\n", $lines), ENT_QUOTES));
                        ?>
                        </td>
                        <td>USD <?php echo number_format($order_full_total,2); ?></td>
                        <td>USD <?php echo number_format($order_total,2); ?></td>
                        <td>USD <?php echo number_format($order_balance,2); ?></td>
                        <td><?php echo $paid_date; ?></td>
                        <td>
                          <?php echo $umrah_date_display; ?>

                          <?php if ($level == '1') { ?>
                            &nbsp;
                            <a href="javascript:void(0);"
                               class="btn btn-sm btn-info btn-edit-umrah"
                               data-id="<?php echo $id; ?>"
                               data-umrah="<?php echo htmlspecialchars(($umrah_date_raw && $umrah_date_raw != '0000-00-00') ? date('Y-m-d', strtotime($umrah_date_raw)) : '', ENT_QUOTES); ?>"
                               title="Update Umrah Date">
                              Change Date
                            </a>
                          <?php } ?>
                        </td>
                        <td><a href="pay_package.php?order_id=<?php echo $order_id;?>&trans_code=<?php echo $trans_code;?>" class="btn btn-success">View Payment History</a></td>
                        <?php
                        }  
                    }
                        ?>
                    </form> 
                    </tr>
                </tbody>
            </table>
            </form>                                 
        </div>
    </div>
</div>                      
</div>
</div>
<!-- ============================================================== -->
<!-- End PAge Content -->

<!-- Umrah Date Modal (Admin Only) -->
<div class="modal fade" id="umrahDateModal" tabindex="-1" role="dialog" aria-labelledby="umrahDateModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <form method="post" action="../Controller/Database_sql.php" onsubmit="return confirm('Update Umrah Date?');">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="umrahDateModalLabel">Update Umrah Date</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>

        <div class="modal-body">
          <input type="hidden" name="order_info_id" id="modal_order_info_id" value="">
          <div class="form-group">
            <label>Umrah Date</label>
            <input type="date" class="form-control" name="umrah_date" id="modal_umrah_date" required>
          </div>
        </div>

        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
          <button type="submit" name="Update_Umrah_Date" class="btn btn-success">
            <i class="fa fa-check"></i> Update
          </button>
        </div>
      </div>
    </form>
  </div>
</div>

</div>
<!-- End Container fluid  -->
</div>
<!-- End Page wrapper  -->

<!-- Footer Start-->
<?php include ("../Footer/footer.php"); ?>
<!-- Footer End-->

</div>
<!-- End Wrapper -->
<!-- All Jquery -->
    

<!-- All Jquery Start-->
<?php include ("../Header/all_jquery.php"); ?>
<!-- All Jquery End-->

<script>
$(document).on('click', '.btn-edit-umrah', function () {
    var id = $(this).data('id');
    var umrah = $(this).data('umrah') || '';

    $('#modal_order_info_id').val(id);
    $('#modal_umrah_date').val(umrah);

    $('#umrahDateModal').modal('show');
});
</script>

</body>

</html>