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

require_once('tcpdf/tcpdf.php');

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

$conn = new mysqli($host, $user, $password, $dbname);

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

$memberNo = $_POST["member_no"] ?? '';
$startDate = $_POST["start_date"] ?? '';
$endDate = $_POST["end_date"] ?? '';

if (!$memberNo) {
    die("Member number is required.");
}

// Fetch member info
$memberStmt = $conn->prepare("SELECT memberName, memberPhoneNo FROM member WHERE memberNo = ?");
$memberStmt->bind_param("s", $memberNo);
$memberStmt->execute();
$memberResult = $memberStmt->get_result();
$member = $memberResult->fetch_assoc();
$memberName = $member['memberName'] ?? 'Unknown';
$memberPhone = $member['memberPhoneNo'] ?? 'N/A';

// Build query for logs
$query = "SELECT * FROM logs WHERE MemberNo = ?";
$params = [$memberNo];
$types = "s";

if (!empty($startDate) && !empty($endDate)) {
    $query .= " AND DATE(paidDate) BETWEEN ? AND ?";
    $params[] = $startDate;
    $params[] = $endDate;
    $types .= "ss";
}

$stmt = $conn->prepare($query);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();

// Initialize TCPDF
$pdf = new TCPDF();
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor("Mkombozi Loan System");
$pdf->SetTitle("Loan Statement");
$pdf->SetMargins(15, 20, 15);
$pdf->AddPage();

// Header
$pdf->SetFont('helvetica', 'B', 16);
$pdf->Cell(0, 10, 'Mkombozi Loan Statement', 0, 1, 'C');
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(0, 6, 'Generated on: ' . date('d M Y, h:i A'), 0, 1, 'C');
$pdf->Ln(5);


// Member info section
$pdf->SetFont('helvetica', '', 11);
$pdf->Cell(0, 6, "Member No: $memberNo", 0, 1);
$pdf->Cell(0, 6, "Name: $memberName", 0, 1);
$pdf->Cell(0, 6, "Phone: $memberPhone", 0, 1);

if (!empty($startDate) && !empty($endDate)) {
    $pdf->Cell(0, 6, "Statement Period: " . date("d-M-Y", strtotime($startDate)) . " to " . date("d-M-Y", strtotime($endDate)), 0, 1);
}

$pdf->Ln(4);

// Table header
$pdf->SetFont('helvetica', 'B', 11);
$pdf->SetFillColor(230, 230, 230);
$pdf->Cell(40, 8, 'Date Paid', 1, 0, 'C', true);
$pdf->Cell(40, 8, 'Amount Paid', 1, 0, 'C', true);
$pdf->Cell(40, 8, 'Loan Balance', 1, 0, 'C', true);
$pdf->Cell(60, 8, 'Receipt No', 1, 1, 'C', true);

// Table content
$pdf->SetFont('helvetica', '', 10);
$totalPaid = 0;
while ($row = $result->fetch_assoc()) {
    $pdf->Cell(40, 7, date('d-m-Y H:i:s', strtotime($row['paidDate'])), 1);
    $pdf->Cell(40, 7, number_format($row['amount_Paid'], 2), 1, 0, 'R');
    $pdf->Cell(40, 7, number_format($row['LoanBalance'], 2), 1, 0, 'R');
    $pdf->Cell(60, 7, $row['receiptNo'], 1, 1);
    $totalPaid += $row['amount_Paid'];
}

// Total row
$pdf->SetFont('helvetica', 'B', 10);
$pdf->Cell(40, 8, 'Total', 1);
$pdf->Cell(40, 8, number_format($totalPaid, 2), 1, 0, 'R');
$pdf->Cell(100, 8, '', 1, 1);

$pdf->Output('loan_statement.pdf', 'D'); //set to I - Open in Browser & D - Download pdf
?>
