<?php
    if (file_exists(__DIR__."/../../pp-config.php")) {
        if (file_exists(__DIR__.'/../../maintenance.lock')) {
            if (file_exists(__DIR__.'/../../pp-include/pp-maintenance.php')) {

            }else{
                die('System is under maintenance. Please try again later.');
            }
            exit();
        }else{
            if (!file_exists(__DIR__.'/../../pp-include/pp-controller.php') || !file_exists(__DIR__.'/../../pp-include/pp-view.php')) {
                echo 'System is under maintenance. Please try again later.';
                exit();
            }

            if (file_exists(__DIR__.'/../../pp-include/pp-model.php')) {
                include(__DIR__."/../../pp-include/pp-model.php");
            }else{
                echo 'System is under maintenance. Please try again later.';
                exit();
            }
        }
    }else{
        die('Configuration file not found');
    }

    if (!defined('pp_allowed_access')) {
        die('Direct access not allowed');
    }

    if(isset($global_user_login) && $global_user_login == true){
        function zyropay_report_count($table, $condition = '') {
            $where = trim($condition) === '' ? '' : 'WHERE '.$condition;
            $response = json_decode(getData($table, $where, 'COUNT(*) as total FROM'), true);

            if (isset($response['response'][0]['total'])) {
                return (int)$response['response'][0]['total'];
            }

            return 0;
        }

        function zyropay_report_money($amount) {
            return is_numeric($amount) ? (float)$amount : 0;
        }

        $default_currency = $global_setting_response['response'][0]['default_currency'] ?? 'BDT';
        $currency_symbol = $global_setting_response['response'][0]['currency_symbol'] ?? '';
        $daily_reports = [];
        $total_amount = 0;
        $today = date('Y-m-d');
        $today_amount = 0;
        $today_transactions = 0;

        $transactions_response = json_decode(getData($db_prefix.'transaction', 'WHERE transaction_status != "initialize" ORDER BY created_at DESC'), true);
        if (!empty($transactions_response['response'])) {
            foreach ($transactions_response['response'] as $transaction) {
                $date_key = date('Y-m-d', strtotime($transaction['created_at'] ?? 'now'));
                $status = strtolower($transaction['transaction_status'] ?? '--');
                $source_currency = $transaction['transaction_currency'] ?? $default_currency;
                $gross_amount = zyropay_report_money($transaction['transaction_amount'] ?? 0) + zyropay_report_money($transaction['transaction_fee'] ?? 0);
                $refund_amount = zyropay_report_money($transaction['transaction_refund_amount'] ?? 0);
                $net_amount = $gross_amount - $refund_amount;
                $converted_amount = convertToDefault($net_amount, $source_currency, $default_currency);

                if (!isset($daily_reports[$date_key])) {
                    $daily_reports[$date_key] = [
                        'date' => $date_key,
                        'total_count' => 0,
                        'completed_count' => 0,
                        'pending_count' => 0,
                        'failed_count' => 0,
                        'refunded_count' => 0,
                        'total_amount' => 0,
                        'completed_amount' => 0,
                        'pending_amount' => 0,
                        'failed_amount' => 0,
                        'refunded_amount' => 0,
                    ];
                }

                $daily_reports[$date_key]['total_count']++;
                $daily_reports[$date_key]['total_amount'] += $converted_amount;
                $total_amount += $converted_amount;

                if ($date_key === $today) {
                    $today_transactions++;
                    $today_amount += $converted_amount;
                }

                if ($status === 'completed') {
                    $daily_reports[$date_key]['completed_count']++;
                    $daily_reports[$date_key]['completed_amount'] += $converted_amount;
                } elseif ($status === 'pending') {
                    $daily_reports[$date_key]['pending_count']++;
                    $daily_reports[$date_key]['pending_amount'] += $converted_amount;
                } elseif ($status === 'failed') {
                    $daily_reports[$date_key]['failed_count']++;
                    $daily_reports[$date_key]['failed_amount'] += $converted_amount;
                } elseif ($status === 'refunded') {
                    $daily_reports[$date_key]['refunded_count']++;
                    $daily_reports[$date_key]['refunded_amount'] += $converted_amount;
                }
            }
        }

        krsort($daily_reports);

        $total_transactions = zyropay_report_count($db_prefix.'transaction', 'transaction_status != "initialize"');
        $completed_transactions = zyropay_report_count($db_prefix.'transaction', 'transaction_status = "completed"');
        $pending_transactions = zyropay_report_count($db_prefix.'transaction', 'transaction_status = "pending"');
        $failed_transactions = zyropay_report_count($db_prefix.'transaction', 'transaction_status = "failed"');
        $refunded_transactions = zyropay_report_count($db_prefix.'transaction', 'transaction_status = "refunded"');
?>
          <div class="page-header">
            <div class="row align-items-center">
              <div class="col">
                <h1 class="page-header-title">Report</h1>
              </div>
            </div>
          </div>

          <div class="row">
            <div class="col-sm-6 col-lg-3 mb-3">
              <div class="card h-100">
                <div class="card-body">
                  <h6 class="card-subtitle">Total Amount</h6>
                  <span class="display-6 fw-semibold"><?php echo $currency_symbol; ?> <?php echo number_format($total_amount, 2); ?></span>
                  <span class="d-block text-muted small"><?php echo htmlspecialchars($default_currency); ?></span>
                </div>
              </div>
            </div>

            <div class="col-sm-6 col-lg-3 mb-3">
              <div class="card h-100">
                <div class="card-body">
                  <h6 class="card-subtitle">Today Amount</h6>
                  <span class="display-6 fw-semibold"><?php echo $currency_symbol; ?> <?php echo number_format($today_amount, 2); ?></span>
                  <span class="d-block text-muted small"><?php echo number_format($today_transactions); ?> transaction</span>
                </div>
              </div>
            </div>

            <div class="col-sm-6 col-lg-3 mb-3">
              <div class="card h-100">
                <div class="card-body">
                  <h6 class="card-subtitle">Total Transaction</h6>
                  <span class="display-6 fw-semibold"><?php echo number_format($total_transactions); ?></span>
                </div>
              </div>
            </div>

            <div class="col-sm-6 col-lg-3 mb-3">
              <div class="card h-100">
                <div class="card-body">
                  <h6 class="card-subtitle">Completed Transaction</h6>
                  <span class="display-6 fw-semibold"><?php echo number_format($completed_transactions); ?></span>
                </div>
              </div>
            </div>

            <div class="col-sm-6 col-lg-3 mb-3">
              <div class="card h-100">
                <div class="card-body">
                  <h6 class="card-subtitle">Pending Transaction</h6>
                  <span class="display-6 fw-semibold"><?php echo number_format($pending_transactions); ?></span>
                </div>
              </div>
            </div>

            <div class="col-sm-6 col-lg-3 mb-3">
              <div class="card h-100">
                <div class="card-body">
                  <h6 class="card-subtitle">Failed Transaction</h6>
                  <span class="display-6 fw-semibold"><?php echo number_format($failed_transactions); ?></span>
                </div>
              </div>
            </div>

            <div class="col-sm-6 col-lg-3 mb-3">
              <div class="card h-100">
                <div class="card-body">
                  <h6 class="card-subtitle">Refunded Transaction</h6>
                  <span class="display-6 fw-semibold"><?php echo number_format($refunded_transactions); ?></span>
                </div>
              </div>
            </div>
          </div>

          <div class="card mt-4">
            <div class="card-header">
              <h4 class="card-header-title">Daily Transaction Report</h4>
            </div>
            <div class="table-responsive">
              <table class="table table-borderless table-thead-bordered table-nowrap table-align-middle card-table">
                <thead class="thead-light">
                  <tr>
                    <th>Date</th>
                    <th>Total Amount</th>
                    <th>Total</th>
                    <th>Completed</th>
                    <th>Pending</th>
                    <th>Failed</th>
                    <th>Refunded</th>
                    <th>Completed Amount</th>
                    <th>Pending Amount</th>
                    <th>Failed Amount</th>
                    <th>Refunded Amount</th>
                  </tr>
                </thead>
                <tbody>
                  <?php if (!empty($daily_reports)): ?>
                    <?php foreach ($daily_reports as $report): ?>
                      <tr>
                        <td><?php echo date('M d, Y', strtotime($report['date'])); ?></td>
                        <td class="fw-semibold"><?php echo $currency_symbol; ?> <?php echo number_format($report['total_amount'], 2); ?></td>
                        <td><?php echo number_format($report['total_count']); ?></td>
                        <td><span class="badge bg-success"><?php echo number_format($report['completed_count']); ?></span></td>
                        <td><span class="badge bg-warning"><?php echo number_format($report['pending_count']); ?></span></td>
                        <td><span class="badge bg-danger"><?php echo number_format($report['failed_count']); ?></span></td>
                        <td><span class="badge bg-secondary"><?php echo number_format($report['refunded_count']); ?></span></td>
                        <td><?php echo $currency_symbol; ?> <?php echo number_format($report['completed_amount'], 2); ?></td>
                        <td><?php echo $currency_symbol; ?> <?php echo number_format($report['pending_amount'], 2); ?></td>
                        <td><?php echo $currency_symbol; ?> <?php echo number_format($report['failed_amount'], 2); ?></td>
                        <td><?php echo $currency_symbol; ?> <?php echo number_format($report['refunded_amount'], 2); ?></td>
                      </tr>
                    <?php endforeach; ?>
                  <?php else: ?>
                    <tr>
                      <td colspan="11" class="text-center py-5 text-muted">No transaction report found</td>
                    </tr>
                  <?php endif; ?>
                </tbody>
              </table>
            </div>
          </div>
<?php
    }
?>
