<?php
/**
 * Rig N Dig - Mobile API v1 / Quotation & Order History
 */
header('Content-Type: application/json');
require_once '../../../config/config.php';
require_once '../../../includes/functions.php';
require_once '../api_helper.php';

$user = authenticateAPI();
$type = $_GET['type'] ?? 'rfq'; // rfq, estimate, po

try {
    if ($type === 'rfq') {
        $data = Database::fetchAll("SELECT id, quote_number, status, created_at, valid_until FROM quotations WHERE customer_id = ? ORDER BY created_at DESC", [$user['id']]);
    } elseif ($type === 'estimate') {
        $data = Database::fetchAll("SELECT id, estimate_number, total, status, created_at, valid_until, pdf_path FROM estimates WHERE customer_id = ? ORDER BY created_at DESC", [$user['id']]);
    } elseif ($type === 'po') {
        $data = Database::fetchAll("SELECT id, po_number, total, status, created_at, delivery_date, pdf_path FROM purchase_orders WHERE customer_id = ? ORDER BY created_at DESC", [$user['id']]);
    } else {
        apiResponse(false, 'Invalid history type');
    }

    // Add full URLs for PDFs
    foreach ($data as &$item) {
        if (!empty($item['pdf_path'])) {
            $item['pdf_url'] = SITE_URL . '/pdf/' . $item['pdf_path'];
        }
    }

    apiResponse(true, 'History loaded', $data);
} catch (Exception $e) {
    apiResponse(false, 'Failed to load history');
}
