<?php
/**
 * ============================================================
 *  বধুবরণ জুয়েলার্স ERP — Sales Module
 *  File: api/sales/get_sales_list.php
 *  Date: 2026-05-16 (v2 — output buffer fix)
 * ============================================================
 */

// === Strict output control ===
ob_start();
@ini_set('display_errors', '0');
error_reporting(E_ERROR | E_PARSE);

require_once __DIR__ . '/../_core.php';

ob_get_clean();

header('Content-Type: application/json; charset=utf-8');

if (!is_logged_in()) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'লগইন করুন']);
    exit;
}

$from_date      = trim($_GET['from_date']      ?? '');
$to_date        = trim($_GET['to_date']        ?? '');
$customer_id    = isset($_GET['customer_id']) ? (int)$_GET['customer_id'] : 0;
$payment_status = $_GET['payment_status']      ?? 'all';
$q              = trim($_GET['q']              ?? '');
$page           = max(1, (int)($_GET['page']     ?? 1));
$per_page       = min(100, max(1, (int)($_GET['per_page'] ?? 20)));
$offset         = ($page - 1) * $per_page;

try {
    $where  = ['1=1'];
    $params = [];

    if ($from_date !== '') {
        $where[]  = 's.sale_date >= ?';
        $params[] = $from_date . ' 00:00:00';
    }
    if ($to_date !== '') {
        $where[]  = 's.sale_date <= ?';
        $params[] = $to_date . ' 23:59:59';
    }
    if ($customer_id > 0) {
        $where[]  = 's.customer_id = ?';
        $params[] = $customer_id;
    }
    if (in_array($payment_status, ['paid', 'partial', 'due'], true)) {
        $where[]  = 's.payment_status = ?';
        $params[] = $payment_status;
    }
    if ($q !== '') {
        $where[]  = '(s.invoice_no LIKE ? OR s.customer_name_snapshot LIKE ? OR s.customer_phone_snapshot LIKE ?)';
        $params[] = "%{$q}%";
        $params[] = "%{$q}%";
        $params[] = "%{$q}%";
    }
    $whereSql = implode(' AND ', $where);

    // Total count
    $countStmt = $pdo->prepare("SELECT COUNT(*) FROM sales s WHERE {$whereSql}");
    $countStmt->execute($params);
    $total = (int)$countStmt->fetchColumn();

    // Paged results
    $sql = "
        SELECT s.id,
               s.invoice_no,
               s.sale_date,
               s.customer_id,
               s.customer_name_snapshot  AS customer_name,
               s.customer_phone_snapshot AS customer_phone,
               s.items_subtotal,
               s.making_charge_total,
               s.vat_amount,
               s.discount_amount,
               s.exchange_value,
               s.grand_total,
               s.paid_total,
               s.due_amount,
               s.payment_status,
               (SELECT COUNT(*) FROM sale_items si WHERE si.sale_id = s.id) AS item_count
          FROM sales s
         WHERE {$whereSql}
         ORDER BY s.id DESC
         LIMIT " . (int)$per_page . " OFFSET " . (int)$offset;

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Summary
    $sumStmt = $pdo->prepare("
        SELECT COALESCE(SUM(grand_total),0) AS sum_grand,
               COALESCE(SUM(paid_total),0)  AS sum_paid,
               COALESCE(SUM(due_amount),0)  AS sum_due
          FROM sales s WHERE {$whereSql}
    ");
    $sumStmt->execute($params);
    $summary = $sumStmt->fetch(PDO::FETCH_ASSOC);

    echo json_encode([
        'ok'          => true,
        'total'       => $total,
        'page'        => $page,
        'per_page'    => $per_page,
        'total_pages' => (int)ceil($total / $per_page),
        'summary'     => [
            'sum_grand_total' => (float)$summary['sum_grand'],
            'sum_paid_total'  => (float)$summary['sum_paid'],
            'sum_due_amount'  => (float)$summary['sum_due'],
        ],
        'results'     => $rows
    ], JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}