<?php
session_start();
error_reporting(0);
include('includes/config.php');
if (strlen($_SESSION['adminlogin']) == 0) {
    header('location:index.php');
    die();
}

function getTotalRecharge($dbh, $period) {
    $sql = "";
    $params = array();

    switch ($period) {
        case 'today':
            $sql = "SELECT SUM(amount) AS total FROM payment WHERE DATE(SUBSTRING_INDEX(paymentExecuteTime, 'T', 1)) = CURDATE()";
            break;
        case 'week':
            $sql = "SELECT SUM(amount) AS total FROM payment WHERE DATE(SUBSTRING_INDEX(paymentExecuteTime, 'T', 1)) BETWEEN CURDATE() - INTERVAL DAYOFWEEK(CURDATE())+6 DAY AND CURDATE()";
            break;
        case 'month':
            $sql = "SELECT SUM(amount) AS total FROM payment WHERE DATE_FORMAT(SUBSTRING_INDEX(paymentExecuteTime, 'T', 1), '%Y-%m') = DATE_FORMAT(CURDATE(), '%Y-%m')";
            break;
        case 'year':
            $sql = "SELECT SUM(amount) AS total FROM payment WHERE YEAR(DATE(SUBSTRING_INDEX(paymentExecuteTime, 'T', 1))) = YEAR(CURDATE())";
            break;
        default:
            return 0;
    }

    $query = $dbh->prepare($sql);
    $query->execute($params);
    $result = $query->fetch(PDO::FETCH_OBJ);
    return $result->total;
}

$selectedPeriod = isset($_POST['period']) ? $_POST['period'] : 'today';
$totalRecharge = getTotalRecharge($dbh, $selectedPeriod);

$searchQuery = isset($_POST['searchQuery']) ? $_POST['searchQuery'] : '';
$searchResults = [];

if (!empty($searchQuery)) {
    $conn = new mysqli($host, $user, $pass, $name);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT * FROM payment WHERE id LIKE ? OR paymentID LIKE ? OR trxID LIKE ? OR customerMsisdn LIKE ? OR email LIKE ?";
    $stmt = $conn->prepare($sql);
    $likeQuery = "%" . $searchQuery . "%";
    $stmt->bind_param("sssss", $likeQuery, $likeQuery, $likeQuery, $likeQuery, $likeQuery);
    $stmt->execute();
    $searchResults = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $conn->close();
}
?>

<!doctype html>
<html lang="en" class="no-js">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <meta name="theme-color" content="#3e454c">

    <title>Recharge History</title>

    <!-- Font awesome -->
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <!-- Sandstone Bootstrap CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <!-- Admin Style -->
    <link rel="stylesheet" href="css/style.css">
    <style>
        .errorWrap {
            padding: 10px;
            margin: 0 0 20px 0;
            background: #dd3d36;
            color: #fff;
            -webkit-box-shadow: 0 1px 1px 0 rgba(0, 0, 0, .1);
            box-shadow: 0 1px 1px 0 rgba(0, 0, 0, .1);
        }

        .succWrap {
            padding: 10px;
            margin: 0 0 20px 0;
            background: #5cb85c;
            color: #fff;
            -webkit-box-shadow: 0 1px 1px 0 rgba(0, 0, 0, .1);
            box-shadow: 0 1px 1px 0 rgba(0, 0, 0, .1);
        }

        .table-container {
            padding: 20px;
            background: #f9f9f9;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        .table-container h1 {
            margin-bottom: 20px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }

        table, th, td {
            border: 1px solid #ddd;
        }

        th, td {
            padding: 12px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        .total {
            font-weight: bold;
            font-size: 1.2em;
        }

        .search-container {
            margin-bottom: 20px;
        }

        .search-container input[type="text"] {
            padding: 6px;
            width: 80%;
            margin-right: 10px;
        }

        .search-container button {
            padding: 6px 12px;
        }
    </style>
</head>

<body>
    <?php include('includes/header.php'); ?>

    <div class="ts-main-content">
        <?php include('includes/leftbar.php'); ?>
        <div class="content-wrapper">
            <div class="container-fluid">

                <div class="row">
                    <div class="col-md-12">

                        <h2 class="page-title">Recharge History</h2>

                        <!-- Recharge Summary Table -->
                        <div class="panel panel-default">
                            <div class="table-container">
                                <h1>Recharge Summary</h1>
                                <form method="post" action="">
                                    <label for="period">Select Period: </label>
                                    <select name="period" id="period" onchange="this.form.submit()">
                                        <option value="today" <?php if ($selectedPeriod == 'today') echo 'selected'; ?>>Today</option>
                                        <option value="week" <?php if ($selectedPeriod == 'week') echo 'selected'; ?>>This Week</option>
                                        <option value="month" <?php if ($selectedPeriod == 'month') echo 'selected'; ?>>This Month</option>
                                        <option value="year" <?php if ($selectedPeriod == 'year') echo 'selected'; ?>>This Year</option>
                                    </select>
                                </form>
                                <table>
                                    <tr>
                                        <th>Time Period</th>
                                        <th>Total Recharge</th>
                                    </tr>
                                    <tr>
                                        <td><?php echo ucfirst($selectedPeriod); ?></td>
                                        <td><?php echo $totalRecharge; ?></td>
                                    </tr>
                                </table>
                            </div>
                        </div>

                        <!-- Payment Records Search -->
                        <div class="panel panel-default">
                            <div class="table-container">
                                <h1>Search Payment Records</h1>
                                <div class="search-container">
                                    <form method="post" action="">
                                        <input type="text" name="searchQuery" placeholder="Enter ID, Payment ID, Transaction ID, Customer Msisdn, Email" value="<?php echo $searchQuery; ?>">
                                        <button type="submit">Search</button>
                                    </form>
                                </div>
                                <?php if (!empty($searchQuery)) : ?>
                                    <h2>Search Results for "<?php echo $searchQuery; ?>"</h2>
                                    <table>
                                        <tr>
                                            <th>ID</th>
                                            <th>Payment ID</th>
                                            <th>Transaction ID</th>
                                            <th>Payment Execute Time</th>
                                            <th>Customer Msisdn</th>
                                            <th>Amount</th>
                                            <th>Email</th>
                                        </tr>
                                        <?php
                                        if (count($searchResults) > 0) {
                                            foreach ($searchResults as $row) {
                                                echo "<tr>
                                                        <td>{$row['id']}</td>
                                                        <td>{$row['paymentID']}</td>
                                                        <td>{$row['trxID']}</td>
                                                        <td>{$row['paymentExecuteTime']}</td>
                                                        <td>{$row['customerMsisdn']}</td>
                                                        <td>{$row['amount']}</td>
                                                        <td>{$row['email']}</td>
                                                      </tr>";
                                            }
                                        } else {
                                            echo "<tr><td colspan='7'>No records found</td></tr>";
                                        }
                                        ?>
                                    </table>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Payment Records Table -->
                        <div class="panel panel-default">
                            <?php
                            $conn = new mysqli($host, $user, $pass, $name);

                            if ($conn->connect_error) {
                                die("Connection failed: " . $conn->connect_error);
                            }

                            $sql = "SELECT id, paymentID, trxID, paymentExecuteTime, customerMsisdn, amount, email FROM payment";
                            $result = $conn->query($sql);
                            ?>

                            <div class="table-container">
                                <h1>Payment Records</h1>
                                <table>
                                    <tr>
                                        <th>ID</th>
                                        <th>Payment ID</th>
                                        <th>Transaction ID</th>
                                        <th>Payment Execute Time</th>
                                        <th>Customer Msisdn</th>
                                        <th>Amount</th>
                                        <th>Email</th>
                                    </tr>
                                    <?php
                                    if ($result->num_rows > 0) {
                                        while($row = $result->fetch_assoc()) {
                                            echo "<tr>
                                                    <td>{$row['id']}</td>
                                                    <td>{$row['paymentID']}</td>
                                                    <td>{$row['trxID']}</td>
                                                    <td>{$row['paymentExecuteTime']}</td>
                                                    <td>{$row['customerMsisdn']}</td>
                                                    <td>{$row['amount']}</td>
                                                    <td>{$row['email']}</td>
                                                  </tr>";
                                        }
                                    } else {
                                        echo "<tr><td colspan='7'>No records found</td></tr>";
                                    }
                                    $conn->close();
                                    ?>
                                </table>
                            </div>
                        </div>

                    </div>
                </div>

            </div>
        </div>
    </div>

    <!-- Loading Scripts -->
    <script src="js/jquery.min.js"></script>
    <script src="js/bootstrap-select.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/main.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            setTimeout(function() {
                $('.succWrap').slideUp("slow");
            }, 3000);
        });
    </script>

</body>

</html>
