<?php
require_once __DIR__ . '/daily_report_helpers.php';

/*
|--------------------------------------------------------------------------
| Load PDF library from vendor
|--------------------------------------------------------------------------
*/
$vendorAutoload = __DIR__ . '/vendor/autoload.php';
if (file_exists($vendorAutoload)) {
    require_once $vendorAutoload;
}

if (!class_exists('TCPDF')) {
    $tcpdfDirect = __DIR__ . '/vendor/tecnickcom/tcpdf/tcpdf.php';
    if (file_exists($tcpdfDirect)) {
        require_once $tcpdfDirect;
    }
}

if (!class_exists('TCPDF')) {
    die('TCPDF library not found in vendor. Please make sure TCPDF is installed.');
}

class KSPDailyReportPDF extends TCPDF
{
    public $reportTitle = '';
    public $reportDate = '';

    public function Header() {
        $logoPath = APP_REPORT_LOGO;
        if (file_exists($logoPath)) {
            $this->Image($logoPath, 14, 10, 18, 18, '', '', '', false, 300, '', false, false, 0, false, false, false);
        }

        $this->SetFont('helvetica', 'B', 14);
        $this->SetXY(36, 10);
        $this->Cell(0, 7, APP_NAME, 0, 1, 'L');

        $this->SetFont('helvetica', '', 9);
        $this->SetX(36);
        $this->Cell(0, 5, APP_ADDRESS_LINE . '  Tel:- ' . APP_PHONE_LINE, 0, 1, 'L');

        $this->Ln(2);

        $this->SetFont('helvetica', 'B', 12);
        $this->Cell(0, 7, $this->reportTitle . ' - As Per - ' . reportDisplayDate($this->reportDate), 0, 1, 'C');
        $this->Ln(2);
    }

    public function Footer() {
        $this->SetY(-20);
        $this->SetFont('helvetica', 'I', 8);
        $this->Cell(0, 5, 'Reports were generated by Krushi Sewa Piyasa System.', 0, 1, 'C');
        $this->Cell(0, 5, APP_NAME . ' - ' . APP_ADDRESS_LINE . '  Tel:- ' . APP_PHONE_LINE, 0, 1, 'C');
    }
}

function reportTableStyle() {
    return '
    <style>
        body { font-family: helvetica; font-size: 10px; }
        table { border-collapse: collapse; width: 100%; }
        th {
            background-color: #dfeefb;
            border: 1px solid #7fa8c9;
            padding: 6px;
            font-weight: bold;
            text-align: center;
        }
        td {
            border: 1px solid #a9bfd3;
            padding: 5px;
            text-align: left;
        }
        .text-right { text-align: right; }
        .text-center { text-align: center; }
        .summary-box {
            margin-top: 12px;
            width: 100%;
        }
        .summary-box td {
            border: 1px solid #7fa8c9;
            padding: 6px;
        }
        .summary-label {
            font-weight: bold;
            background-color: #eef6fc;
        }
        .section-gap {
            height: 8px;
        }
    </style>';
}

function generateDailyReportPdf($date = null, $saveMode = 'F') {
    global $conn;

    $date = $date ?: date('Y-m-d');
    $outputPath = reportFilePath($date);

    $saleReport = getDailySaleIncomeProfitReport($conn, $date);
    $purchasingReport = getDailyPurchasingReport($conn, $date);
    $stockReport = getAvailableStocksReport($conn, $date);
    $creditSaleReport = getDailyCreditSaleReport($conn, $date);

    $pdf = new KSPDailyReportPDF('P', 'mm', 'A4', true, 'UTF-8', false);
    $pdf->SetCreator(APP_NAME);
    $pdf->SetAuthor(APP_NAME);
    $pdf->SetTitle(reportFileName($date));
    $pdf->SetMargins(12, 34, 12);
    $pdf->SetHeaderMargin(6);
    $pdf->SetFooterMargin(8);
    $pdf->SetAutoPageBreak(true, 24);
    $pdf->SetFont('helvetica', '', 10);

    /*
    |--------------------------------------------------------------------------
    | Page 1 - Daily Sale / Income / Profit
    |--------------------------------------------------------------------------
    */
    $pdf->reportTitle = 'Daily Sale-Income-Profit';
    $pdf->reportDate = $date;
    $pdf->AddPage();

    $html = reportTableStyle();
    $html .= '<table>
        <tr>
            <th width="18%">Date</th>
            <th width="24%">Bill Number</th>
            <th width="19%">Per Bill Sale</th>
            <th width="19%">Per Bill Income</th>
            <th width="20%">Per Bill Profit</th>
        </tr>';

    foreach ($saleReport['rows'] as $row) {
        $html .= '<tr>
            <td>' . htmlspecialchars(reportDisplayDate($row['entered_date'])) . '</td>
            <td>' . htmlspecialchars($row['bill_number']) . '</td>
            <td class="text-right">' . moneyFormatReport($row['per_bill_sale']) . '</td>
            <td class="text-right">' . moneyFormatReport($row['per_bill_income']) . '</td>
            <td class="text-right">' . moneyFormatReport($row['per_bill_profit']) . '</td>
        </tr>';
    }

    if (empty($saleReport['rows'])) {
        $html .= '<tr><td colspan="5" class="text-center">No records found for this date.</td></tr>';
    }

    $html .= '</table>';

    $html .= '<table class="summary-box">
        <tr>
            <td class="summary-label" width="65%">Total Sale</td>
            <td class="text-right" width="35%">' . moneyFormatReport($saleReport["totals"]["total_sale"]) . '</td>
        </tr>
        <tr>
            <td class="summary-label">Total Income</td>
            <td class="text-right">' . moneyFormatReport($saleReport["totals"]["total_income"]) . '</td>
        </tr>
        <tr>
            <td class="summary-label">Total Profit</td>
            <td class="text-right">' . moneyFormatReport($saleReport["totals"]["total_profit"]) . '</td>
        </tr>
    </table>';

    $pdf->writeHTML($html, true, false, true, false, '');

    /*
    |--------------------------------------------------------------------------
    | Page 2 - Daily Purchasing
    |--------------------------------------------------------------------------
    */
    $pdf->reportTitle = 'Daily Purchasing';
    $pdf->reportDate = $date;
    $pdf->AddPage();

    $html = reportTableStyle();
    $html .= '<table>
        <tr>
            <th width="18%">Date</th>
            <th width="22%">Invoice Number</th>
            <th width="20%">Company</th>
            <th width="14%">Total Amount</th>
            <th width="13%">Paid Amount</th>
            <th width="13%">Balance Amount</th>
        </tr>';

    foreach ($purchasingReport['rows'] as $row) {
        $html .= '<tr>
            <td>' . htmlspecialchars(reportDisplayDate($row['report_date'])) . '</td>
            <td>' . htmlspecialchars($row['invoice_number']) . '</td>
            <td>' . htmlspecialchars($row['supplier']) . '</td>
            <td class="text-right">' . moneyFormatReport($row['total_amount']) . '</td>
            <td class="text-right">' . moneyFormatReport($row['paid_amount']) . '</td>
            <td class="text-right">' . moneyFormatReport($row['pending_amount']) . '</td>
        </tr>';
    }

    if (empty($purchasingReport['rows'])) {
        $html .= '<tr><td colspan="6" class="text-center">No records found for this date.</td></tr>';
    }

    $html .= '</table>';

    $html .= '<table class="summary-box">
        <tr>
            <td class="summary-label" width="65%">Total Purchasing</td>
            <td class="text-right" width="35%">' . moneyFormatReport($purchasingReport["totals"]["total_purchasing"]) . '</td>
        </tr>
        <tr>
            <td class="summary-label">Total Payable</td>
            <td class="text-right">' . moneyFormatReport($purchasingReport["totals"]["total_payable"]) . '</td>
        </tr>
        <tr>
            <td class="summary-label">Total Credits</td>
            <td class="text-right">' . moneyFormatReport($purchasingReport["totals"]["total_credits"]) . '</td>
        </tr>
    </table>';

    $pdf->writeHTML($html, true, false, true, false, '');

    /*
    |--------------------------------------------------------------------------
    | Page 3 - Available Stocks
    |--------------------------------------------------------------------------
    */
    $pdf->reportTitle = 'Available Stock';
    $pdf->reportDate = $date;
    $pdf->AddPage();

    $html = reportTableStyle();
    $html .= '<table>
        <tr>
            <th width="18%">Date</th>
            <th width="46%">Products</th>
            <th width="18%">QTY</th>
            <th width="18%">Unit</th>
        </tr>';

    foreach ($stockReport['rows'] as $row) {
        $html .= '<tr>
            <td>' . htmlspecialchars(reportDisplayDate($row['report_date'])) . '</td>
            <td>' . htmlspecialchars($row['product_name']) . '</td>
            <td class="text-right">' . number_format((float)$row['purchased_qty'], 2) . '</td>
            <td class="text-center">' . htmlspecialchars($row['unit']) . '</td>
        </tr>';
    }

    if (empty($stockReport['rows'])) {
        $html .= '<tr><td colspan="4" class="text-center">No records found.</td></tr>';
    }

    $html .= '</table>';

    $pdf->writeHTML($html, true, false, true, false, '');

    /*
    |--------------------------------------------------------------------------
    | Page 4 - Daily Credit Sale
    |--------------------------------------------------------------------------
    */
    $pdf->reportTitle = 'Credit Sale';
    $pdf->reportDate = $date;
    $pdf->AddPage();

    $html = reportTableStyle();
    $html .= '<table>
        <tr>
            <th width="18%">Date</th>
            <th width="24%">Creditor</th>
            <th width="22%">Bill Number</th>
            <th width="18%">Bill Amount</th>
            <th width="18%">Credit Balance</th>
        </tr>';

    foreach ($creditSaleReport['rows'] as $row) {
        $html .= '<tr>
            <td>' . htmlspecialchars(reportDisplayDate($row['entered_date'])) . '</td>
            <td>' . htmlspecialchars($row['customer_name']) . '</td>
            <td>' . htmlspecialchars($row['bill_number']) . '</td>
            <td class="text-right">' . moneyFormatReport($row['total_amount']) . '</td>
            <td class="text-right">' . moneyFormatReport($row['balance_amount']) . '</td>
        </tr>';
    }

    if (empty($creditSaleReport['rows'])) {
        $html .= '<tr><td colspan="5" class="text-center">No records found for this date.</td></tr>';
    }

    $html .= '</table>';

    $html .= '<table class="summary-box">
        <tr>
            <td class="summary-label" width="65%">Total Credit Balance</td>
            <td class="text-right" width="35%">' . moneyFormatReport($creditSaleReport["total_credit_balance"]) . '</td>
        </tr>
    </table>';

    if (!empty($creditSaleReport['summary_rows'])) {
        $html .= '<div class="section-gap"></div>';
        $html .= '<table>
            <tr>
                <th width="45%">Creditor Name</th>
                <th width="20%">Bill Count</th>
                <th width="35%">Total Credit Amount to Pay</th>
            </tr>';

        foreach ($creditSaleReport['summary_rows'] as $row) {
            $html .= '<tr>
                <td>' . htmlspecialchars($row['customer_name']) . '</td>
                <td class="text-center">' . (int)$row['bill_count'] . '</td>
                <td class="text-right">' . moneyFormatReport($row['total_credit_amount']) . '</td>
            </tr>';
        }

        $html .= '</table>';
    }

    $pdf->writeHTML($html, true, false, true, false, '');

    $pdf->Output($outputPath, $saveMode);

    return $outputPath;
}
?>