<?php

include "config.php";
require_once('tcpdf/tcpdf.php');

$start = $_GET['start'];
$end   = $_GET['end'];
$user_id = $_GET['user_id'];
$customer_id = $_GET['customer_id'];

if($customer_id == 0)
{
    $stmt = $pdo->prepare("
        SELECT t.*, c.name AS customer_name
        FROM transactions t
        LEFT JOIN customers c ON c.id = t.customer_id
        WHERE t.user_id=?
        AND t.trans_date BETWEEN ? AND ?
        ORDER BY t.trans_date
    ");

    $stmt->execute([$user_id,$start,$end]);
}
else
{
    $stmt = $pdo->prepare("
        SELECT t.*, c.name AS customer_name
        FROM transactions t
        LEFT JOIN customers c ON c.id = t.customer_id
        WHERE t.user_id=?
        AND t.customer_id=?
        AND t.trans_date BETWEEN ? AND ?
        ORDER BY t.trans_date
    ");

    $stmt->execute([$user_id,$customer_id,$start,$end]);
}


$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$pdf = new TCPDF();
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);

$pdf->AddPage();

$html = "<html><body><h2>Income Expense Report</h2><br><br>";

$html .= '<table border="1" cellpadding="5">
<tr>
<th>Date</th>
<th>Type</th>
<th>Title</th>
<th  style="text-align:right">Income (Rs.)</th>
<th  style="text-align:right">Expense (Rs.)</th>
</tr>';

$total_income = 0;
$total_expense = 0;

foreach($rows as $row)
{
    $income=strtolower($row['type'])=='income'? $row['amount'] : 0;
    $expense=strtolower($row['type'])=='expense'? $row['amount'] : 0;
    $html .= '<tr>
    <td>'.$row["trans_date"].'</td>
    <td>'.$row["type"].'</td>
    <td>'.$row["title"].'</td>
    <td  style="text-align:right">'.number_format($income,2).'</td>
    <td  style="text-align:right">'.number_format($expense,2).'</td>
    </tr>';

    if(strtolower($row['type'])=="income")
        $total_income += $row['amount'];
    else
        $total_expense += $row['amount'];
}
$html .= '<tr>
    <td colspan="3" style="text-align:right">Total (Rs.)</td>
    <td  style="text-align:right">'.number_format($total_income,2).'</td>
    <td  style="text-align:right">'.number_format($total_expense,2).'</td>
    </tr>';
$html .= "</table></body></html>";

$pdf->writeHTML($html);

$pdf->Output("report.pdf","I");