<?php
declare(strict_types=1);

if (basename(__FILE__) === basename($_SERVER['SCRIPT_FILENAME'] ?? '')) {
    http_response_code(403);
    exit('Forbidden');
}

const PRODUCT_CATEGORIES = ['Solar Panel', 'Inverter', 'Battery', 'Structure', 'Cable', 'Protection', 'Accessories', 'Service', 'Installation', 'Custom'];
const PRODUCT_UNITS = ['pcs', 'set', 'meter', 'feet', 'kg', 'lot', 'service'];
const PRODUCT_STATUSES = ['active', 'inactive'];
const PRODUCT_CSV_HEADER = ['product_category', 'product_name', 'description', 'brand', 'model', 'unit', 'unit_price', 'status'];

function can_manage_products(): bool
{
    return can('*');
}

function can_export_products(): bool
{
    return in_array(current_user()['role'] ?? '', ['admin', 'sales'], true);
}

function validate_product_input(array $input): array
{
    $data = [
        'product_category' => trim((string)($input['product_category'] ?? '')),
        'product_name' => trim((string)($input['product_name'] ?? '')),
        'description' => trim((string)($input['description'] ?? '')),
        'brand' => trim((string)($input['brand'] ?? '')),
        'model' => trim((string)($input['model'] ?? '')),
        'unit' => trim((string)($input['unit'] ?? '')),
        'unit_price' => trim((string)($input['unit_price'] ?? '')),
        'status' => trim((string)($input['status'] ?? 'active')),
    ];
    $errors = [];
    if (!in_array($data['product_category'], PRODUCT_CATEGORIES, true)) {
        $errors[] = 'Product category is invalid.';
    }
    if ($data['product_name'] === '') {
        $errors[] = 'Product name is required.';
    }
    if ($data['unit'] === '') {
        $errors[] = 'Unit is required.';
    }
    if ($data['unit_price'] === '' || !is_numeric($data['unit_price']) || (float)$data['unit_price'] < 0) {
        $errors[] = 'Unit price must be numeric and non-negative.';
    }
    if (!in_array($data['status'], PRODUCT_STATUSES, true)) {
        $errors[] = 'Status is invalid.';
    }
    $data['unit_price'] = (float)$data['unit_price'];
    return [$data, $errors];
}

function duplicate_product_exists(array $data, int $ignoreId = 0): bool
{
    $stmt = db()->prepare('SELECT id FROM products WHERE product_name = ? AND brand = ? AND model = ? AND id <> ? LIMIT 1');
    $stmt->execute([$data['product_name'], $data['brand'], $data['model'], $ignoreId]);
    return (bool)$stmt->fetch();
}

function product_filter_sql(array $query): array
{
    $where = [];
    $params = [];
    $search = trim((string)($query['search'] ?? ''));
    if ($search !== '') {
        $where[] = '(product_name LIKE ? OR brand LIKE ? OR model LIKE ?)';
        $like = '%' . $search . '%';
        array_push($params, $like, $like, $like);
    }
    $category = trim((string)($query['category'] ?? ''));
    if ($category !== '' && in_array($category, PRODUCT_CATEGORIES, true)) {
        $where[] = 'product_category = ?';
        $params[] = $category;
    }
    $brand = trim((string)($query['brand'] ?? ''));
    if ($brand !== '') {
        $where[] = 'brand = ?';
        $params[] = $brand;
    }
    $status = trim((string)($query['status'] ?? ''));
    if ($status !== '' && in_array($status, PRODUCT_STATUSES, true)) {
        $where[] = 'status = ?';
        $params[] = $status;
    }
    return [$where ? 'WHERE ' . implode(' AND ', $where) : '', $params];
}

function fetch_filtered_products(array $query): array
{
    [$where, $params] = product_filter_sql($query);
    $stmt = db()->prepare("SELECT * FROM products $where ORDER BY product_category, product_name, brand, model");
    $stmt->execute($params);
    return $stmt->fetchAll();
}

function csv_download_headers(string $filename): void
{
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
}
