<?php
//start session
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    header("Location: index.php");
    exit;
}


// Database connection
include("include/connection.php");


$conn = new mysqli($host, $user, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$memberNo = "";
$startDate = "";
$endDate = "";
$results = [];
$memberDetails = null;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $memberNo = $_POST["member_no"];
    $startDate = $_POST["start_date"] ?? "";
    $endDate = $_POST["end_date"] ?? "";

    // Fetch member info
    $memberSql = "SELECT memberNo, memberName, memberPhoneNo FROM member WHERE memberNo = ?";
    $stmt = $conn->prepare($memberSql);
    $stmt->bind_param("s", $memberNo);
    $stmt->execute();
    $result = $stmt->get_result();
    $memberDetails = $result->fetch_assoc();
    $stmt->close();

    // Build logs query with optional date filters
    $sql = "SELECT * FROM logs WHERE MemberNo = ?";
    if (!empty($startDate) && !empty($endDate)) {
        $sql .= " AND paidDate BETWEEN ? AND ?";
    }

    $stmt = $conn->prepare($sql);

    if (!empty($startDate) && !empty($endDate)) {
        $stmt->bind_param("sss", $memberNo, $startDate, $endDate);
    } else {
        $stmt->bind_param("s", $memberNo);
    }

    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $results[] = $row;
    }

    $stmt->close();
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Loan Collection Statement</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">

<div class="container mt-5">
    <h2 class="text-center mb-4">Loan Collection Statement</h2>

    <form method="post" class="mb-4">
        <div class="row">
            <div class="col-md-3">
                <label for="member_no" class="form-label">Member Number:</label>
                <input type="text" id="member_no" name="member_no" class="form-control" required value="<?= htmlspecialchars($memberNo) ?>">
            </div>
            <div class="col-md-3">
                <label for="start_date" class="form-label">Start Date:</label>
                <input type="date" id="start_date" name="start_date" class="form-control" value="<?= htmlspecialchars($startDate) ?>">
            </div>
            <div class="col-md-3">
                <label for="end_date" class="form-label">End Date:</label>
                <input type="date" id="end_date" name="end_date" class="form-control" value="<?= htmlspecialchars($endDate) ?>">
            </div>
            <div class="col-md-3 align-self-end">
                <button type="submit" class="btn btn-primary w-100">Get Statement</button>
            </div>
        </div>
    </form>

    <?php if ($memberDetails): ?>
        <div class="mb-4">
            <h5>Member Information:</h5>
            <ul class="list-group">
                <li class="list-group-item"><strong>Member No:</strong> <?= htmlspecialchars($memberDetails['memberNo']) ?> , 
											<strong>Name:</strong> <?= htmlspecialchars($memberDetails['memberName']) ?>,
											<strong>Phone:</strong> <?= htmlspecialchars($memberDetails['memberPhoneNo']) ?>
				</li>
            </ul>
        </div>
    <?php endif; ?>

    <?php if (!empty($results)) : ?>
	
	        <form action="export_pdf.php" method="post" target="_blank">
            <input type="hidden" name="member_no" value="<?= htmlspecialchars($memberNo) ?>">
            <input type="hidden" name="start_date" value="<?= htmlspecialchars($startDate) ?>">
            <input type="hidden" name="end_date" value="<?= htmlspecialchars($endDate) ?>">
            <button type="submit" class="btn btn-danger mt-3">Export to PDF</button>
        </form>
		
        <table class="table table-bordered table-striped">
            <thead class="table-dark">
                <tr>
                    <th>Paid Date</th>
                    <th>Amount Paid</th>
                    <th>Loan Balance</th>
                    <th>Receipt No</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($results as $row) : ?>
                    <tr>
                        <td><?= htmlspecialchars($row['paidDate']) ?></td>
                        <td><?= number_format($row['amount_Paid'], 2) ?></td>
                        <td><?= number_format($row['LoanBalance']) ?></td>
                        <td><?= htmlspecialchars($row['receiptNo']) ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

 <!--       <form action="export_pdf.php" method="post" target="_blank">
            <input type="hidden" name="member_no" value="<?= htmlspecialchars($memberNo) ?>">
            <input type="hidden" name="start_date" value="<?= htmlspecialchars($startDate) ?>">
            <input type="hidden" name="end_date" value="<?= htmlspecialchars($endDate) ?>">
            <button type="submit" class="btn btn-danger mt-3">Export to PDF</button>
        </form>
-->

    <?php elseif ($_SERVER["REQUEST_METHOD"] == "POST") : ?>
        <div class="alert alert-warning text-center">No records found for Member No: <?= htmlspecialchars($memberNo) ?></div>
    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
