<?php
require_once __DIR__ . '/config.php';
require_auth();

$db = get_db();
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $productGroupId = $_GET['product_group_id'] ?? null;
    $search = trim($_GET['search'] ?? '');
    $status = $_GET['status'] ?? null;

    $sql = '
        SELECT c.*, s.style_code, s.style_name, s.colour, s.gender, s.size_curve, s.season, s.status AS style_status,
               pg.code AS product_group_code, pg.name AS product_group_name
        FROM costings c
        JOIN styles s ON s.id = c.style_id
        JOIN product_groups pg ON pg.id = s.product_group_id
        WHERE 1=1
    ';
    $params = [];

    if ($productGroupId) {
        $sql .= ' AND s.product_group_id = ?';
        $params[] = $productGroupId;
    }
    if ($status) {
        $sql .= ' AND s.status = ?';
        $params[] = $status;
    }
    if ($search !== '') {
        $sql .= ' AND (s.style_code LIKE ? OR s.style_name LIKE ? OR s.colour LIKE ?)';
        $like = "%$search%";
        array_push($params, $like, $like, $like);
    }

    $sql .= ' ORDER BY c.effective_date DESC, s.style_code';

    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    respond($stmt->fetchAll());
}

if ($method === 'POST') {
    $input = json_input();
    $required = ['style_id', 'effective_date', 'std_price', 'group_price', 'rrp', 'base_cost'];
    foreach ($required as $field) {
        if (!isset($input[$field]) || $input[$field] === '') {
            respond(['error' => "$field is required"], 422);
        }
    }

    $duty = (float)($input['duty'] ?? 0);
    $landing = (float)($input['landing'] ?? 0);
    $freight = (float)($input['freight'] ?? 0);
    $overheadPackage = (float)($input['overhead_package'] ?? 0);
    $overheadInsurance = (float)($input['overhead_insurance'] ?? 0);
    $rejection = (float)($input['rejection_cost'] ?? 0);
    $selling = (float)($input['selling_cost'] ?? 0);
    $baseCost = (float)$input['base_cost'];
    $totalCost = $baseCost + $duty + $landing + $freight + $overheadPackage + $overheadInsurance + $rejection + $selling;

    $stmt = $db->prepare('
        INSERT INTO costings
            (style_id, effective_date, delivery_from, delivery_to, std_price, group_price, rrp,
             base_cost, duty, landing, freight, overhead_package, overhead_insurance, rejection_cost,
             selling_cost, total_cost, status)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ');
    $stmt->execute([
        $input['style_id'],
        $input['effective_date'],
        $input['delivery_from'] ?? null,
        $input['delivery_to'] ?? null,
        $input['std_price'],
        $input['group_price'],
        $input['rrp'],
        $baseCost,
        $duty,
        $landing,
        $freight,
        $overheadPackage,
        $overheadInsurance,
        $rejection,
        $selling,
        $totalCost,
        $input['status'] ?? 'Pending Approval',
    ]);

    respond(['id' => $db->lastInsertId(), 'total_cost' => $totalCost], 201);
}

respond(['error' => 'Method not allowed'], 405);
