<?php
/**
 * GET /api/orders/sales_history.php
 * Any logged-in account (business or personal - both can sell) sees their
 * own sold-item history here. This is the seller-side counterpart to
 * orders/list.php (which is the buyer-side purchase history).
 *
 * Query params: status (pending|fulfilled|cancelled), date_from, date_to,
 * search (product name), page.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

$sellerId = require_login();

$page = max(1, (int) ($_GET['page'] ?? 1));
$perPage = 25;
$offset = ($page - 1) * $perPage;

$pdo = Database::connect();

$where = ['oi.seller_id = ?'];
$params = [$sellerId];

if (!empty($_GET['status']) && in_array($_GET['status'], ['pending', 'fulfilled', 'cancelled'], true)) {
    $where[] = 'oi.status = ?';
    $params[] = $_GET['status'];
}
if (!empty($_GET['date_from'])) {
    $where[] = 'DATE(o.created_at) >= ?';
    $params[] = $_GET['date_from'];
}
if (!empty($_GET['date_to'])) {
    $where[] = 'DATE(o.created_at) <= ?';
    $params[] = $_GET['date_to'];
}
if (!empty($_GET['search'])) {
    $where[] = 'p.name LIKE ?';
    $params[] = '%' . $_GET['search'] . '%';
}

$whereSql = 'WHERE ' . implode(' AND ', $where);

$countStmt = $pdo->prepare("
    SELECT COUNT(*) FROM order_items oi
    JOIN orders o ON o.id = oi.order_id
    JOIN products p ON p.id = oi.product_id
    $whereSql
");
$countStmt->execute($params);
$total = (int) $countStmt->fetchColumn();

$stmt = $pdo->prepare("
    SELECT oi.id AS order_item_id, oi.order_id, oi.quantity, oi.unit_price, oi.status,
           (oi.quantity * oi.unit_price) AS line_total,
           o.created_at AS order_date,
           p.id AS product_id, p.name AS product_name,
           (SELECT image_path FROM product_images pi WHERE pi.product_id = p.id ORDER BY sort_order ASC LIMIT 1) AS thumbnail,
           buyer.email AS buyer_email,
           COALESCE(bpr.full_name, bbp.business_name) AS buyer_name
    FROM order_items oi
    JOIN orders o ON o.id = oi.order_id
    JOIN products p ON p.id = oi.product_id
    JOIN users buyer ON buyer.id = o.buyer_id
    LEFT JOIN personal_profiles bpr ON bpr.user_id = buyer.id
    LEFT JOIN business_profiles bbp ON bbp.user_id = buyer.id
    $whereSql
    ORDER BY o.created_at DESC
    LIMIT $perPage OFFSET $offset
");
$stmt->execute($params);
$rows = $stmt->fetchAll();

foreach ($rows as &$r) {
    $r['thumbnail_url'] = $r['thumbnail'] ? UPLOAD_URL . $r['thumbnail'] : null;
    unset($r['thumbnail']);
}

send_json(true, 'OK', [
    'items' => $rows,
    'pagination' => ['page' => $page, 'per_page' => $perPage, 'total' => $total, 'total_pages' => (int) ceil($total / $perPage)],
]);
