<?php
/**
 * Invoices List Endpoint (Role-Based & Tenant-Aware)
 */

use App\Core\Database;
use App\Core\Encryption;
use App\Middleware\AuthMiddleware;

// 1. Auth Check
$decoded = AuthMiddleware::check();
$db = Database::getInstance();

$tenantId = $decoded['tenant_id'];
$userId = $decoded['user_id'];
$role = $decoded['role'];

try {
    // 2. Build Query based on Role
    if ($role === 'super_admin') {
        // Super Admin sees ALL invoices
        $stmt = $db->query("
            SELECT i.*, t.name as tenant_name, c.name as company_name
            FROM invoices i
            LEFT JOIN tenants t ON i.tenant_id = t.id
            LEFT JOIN companies c ON i.company_id = c.id
            ORDER BY i.created_at DESC
        ");
    } elseif ($role === 'admin') {
        // Admin sees all invoices in THEIR tenant
        $stmt = $db->prepare("
            SELECT i.*, c.name as company_name
            FROM invoices i
            LEFT JOIN companies c ON i.company_id = c.id
            WHERE i.tenant_id = ?
            ORDER BY i.created_at DESC
        ");
        $stmt->execute([$tenantId]);
    } else {
        // Accountant/Viewer: Filter by assigned companies
        $stmtUser = $db->prepare("SELECT company_id FROM user_company_assignments WHERE user_id = ? AND is_active = 1");
        $stmtUser->execute([$userId]);
        $assignedCompanyIds = $stmtUser->fetchAll(PDO::FETCH_COLUMN);

        if (empty($assignedCompanyIds)) {
            json_success([]);
        }

        $placeholders = implode(',', array_fill(0, count($assignedCompanyIds), '?'));
        $stmt = $db->prepare("
            SELECT i.*, c.name as company_name
            FROM invoices i
            LEFT JOIN companies c ON i.company_id = c.id
            WHERE i.company_id IN ($placeholders)
            ORDER BY i.created_at DESC
        ");
        $stmt->execute($assignedCompanyIds);
    }

    $invoices = $stmt->fetchAll();

    // 3. Decrypt sensitive fields for display (Robustly)
    $dec = function($val) {
        if (empty($val)) return '';
        $result = \App\Core\Encryption::decrypt((string)$val);
        return ($result !== false && $result !== null) ? $result : (string)$val;
    };

    foreach ($invoices as &$inv) {
        $inv['supplier_name'] = $dec($inv['supplier_name']);
        $inv['supplier_tin'] = $dec($inv['supplier_tin']);
        $inv['buyer_name'] = $dec($inv['buyer_name']);
        
        if (!empty($inv['company_name'])) {
            $inv['company_name'] = $dec($inv['company_name']);
        }
        if (!empty($inv['tenant_name'])) {
            $inv['tenant_name'] = $dec($inv['tenant_name']);
        }
    }

    if (empty($invoices)) {
        error_log("INVOICES LIST: No invoices found for role: $role, tenant_id: $tenantId");
    }

    json_success($invoices);

} catch (\Exception $e) {
    json_error('SQL Error in Invoices List: ' . $e->getMessage(), 500);
}
