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

function ensureReportDirectory() {
    if (!is_dir(APP_REPORT_DIR)) {
        mkdir(APP_REPORT_DIR, 0775, true);
    }
}

function reportDisplayDate($date) {
    return strtoupper(date('Y-M-j', strtotime($date)));
}

function reportFileDate($date) {
    return strtoupper(date('Y-F-d', strtotime($date)));
}

function reportFileName($date) {
    return 'KSP-Daily Report-' . reportFileDate($date) . '.pdf';
}

function reportFilePath($date) {
    ensureReportDirectory();
    return APP_REPORT_DIR . '/' . reportFileName($date);
}

function moneyFormatReport($amount) {
    $amount = (float)$amount;
    $prefix = $amount < 0 ? '-Rs. ' : 'Rs. ';
    return $prefix . number_format(abs($amount), 2);
}

function getAdminReportRecipients(mysqli $conn) {
    $emails = [];

    $stmt = $conn->prepare("SELECT email FROM user WHERE user_category = 'Admin' AND email IS NOT NULL AND email != '' ORDER BY id ASC");
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $email = trim($row['email']);
        if ($email !== '') {
            $emails[] = $email;
        }
    }

    return array_values(array_unique($emails));
}

function getDailySaleIncomeProfitReport(mysqli $conn, $date) {
    $rows = [];
    $totals = [
        'total_sale' => 0,
        'total_income' => 0,
        'total_profit' => 0
    ];

    $stmt = $conn->prepare("
        SELECT 
            entered_date,
            bill_number,
            IFNULL(SUM(purchaing_amount), 0) AS per_bill_sale,
            IFNULL(SUM(sell_amount), 0) AS per_bill_income,
            IFNULL(SUM(profit), 0) AS per_bill_profit
        FROM income_profit_data
        WHERE entered_date = ?
        GROUP BY entered_date, bill_number
        ORDER BY bill_number ASC
    ");
    $stmt->bind_param("s", $date);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
        $totals['total_sale'] += (float)$row['per_bill_sale'];
        $totals['total_income'] += (float)$row['per_bill_income'];
        $totals['total_profit'] += (float)$row['per_bill_profit'];
    }

    return ['rows' => $rows, 'totals' => $totals];
}

function getDailyPurchasingReport(mysqli $conn, $date) {
    $rows = [];
    $totals = [
        'total_purchasing' => 0,
        'total_payable' => 0,
        'total_credits' => 0
    ];

    $stmt = $conn->prepare("
        SELECT
            COALESCE(purchase_date, entered_date) AS report_date,
            invoice_number,
            supplier,
            total_amount,
            paid_amount,
            pending_amount
        FROM credit_puraching
        WHERE entered_date = ?
        ORDER BY id ASC
    ");
    $stmt->bind_param("s", $date);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
        $totals['total_purchasing'] += (float)$row['total_amount'];
        $totals['total_payable'] += (float)$row['paid_amount'];
        $totals['total_credits'] += (float)$row['pending_amount'];
    }

    return ['rows' => $rows, 'totals' => $totals];
}

function getAvailableStocksReport(mysqli $conn, $date) {
    $rows = [];

    $result = $conn->query("
        SELECT product_name, purchased_qty, unit
        FROM stock
        ORDER BY product_name ASC
    ");

    while ($row = $result->fetch_assoc()) {
        $rows[] = [
            'report_date' => $date,
            'product_name' => $row['product_name'],
            'purchased_qty' => $row['purchased_qty'],
            'unit' => $row['unit']
        ];
    }

    return ['rows' => $rows];
}

function getDailyCreditSaleReport(mysqli $conn, $date) {
    $rows = [];
    $summaryRows = [];
    $totalCreditBalance = 0;

    $stmt = $conn->prepare("
        SELECT
            entered_date,
            customer_name,
            bill_number,
            total_amount,
            balance_amount
        FROM credit_sale_data
        WHERE entered_date = ?
        ORDER BY id ASC
    ");
    $stmt->bind_param("s", $date);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
        $totalCreditBalance += (float)$row['balance_amount'];
    }

    $summaryStmt = $conn->prepare("
        SELECT
            customer_name,
            COUNT(DISTINCT bill_number) AS bill_count,
            IFNULL(SUM(balance_amount), 0) AS total_credit_amount
        FROM credit_sale_data
        WHERE entered_date = ?
        GROUP BY customer_name
        ORDER BY customer_name ASC
    ");
    $summaryStmt->bind_param("s", $date);
    $summaryStmt->execute();
    $summaryResult = $summaryStmt->get_result();

    while ($row = $summaryResult->fetch_assoc()) {
        $summaryRows[] = $row;
    }

    return [
        'rows' => $rows,
        'summary_rows' => $summaryRows,
        'total_credit_balance' => $totalCreditBalance
    ];
}
?>