<?php
require 'auth_check.php';
require_once 'db.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
if (!$id) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing or invalid transaction ID']);
    exit;
}

$data = [
    'po_date'                 => $_POST['po_date']                 ?? null,
    'po_number'               => $_POST['po_number']               ?? null,
    'inv_date'                => $_POST['inv_date']                ?? null,
    'inv_number'              => $_POST['inv_number']              ?? null,
    'vendor'                  => $_POST['vendor']                  ?? null,
    'item'                    => $_POST['item']                    ?? null,
    'department'              => $_POST['department']              ?? null,
    'department_remarks'      => $_POST['department_remarks']      ?? null,
    'unit'                    => isset($_POST['unit'])   ? (float) str_replace(',', '', $_POST['unit'])   : 0,
    'uom'                     => $_POST['uom']                     ?? null,
    'price'                   => isset($_POST['price'])  ? (float) str_replace(',', '', $_POST['price'])  : 0,
    'row_remarks'             => $_POST['row_remarks']             ?? null,
    'sst'                     => isset($_POST['sst'])    ? (float) str_replace(',', '', $_POST['sst'])    : 0,
    'total_price'             => isset($_POST['total_price']) ? (float) str_replace(',', '', $_POST['total_price']) : 0,
    'min_amount_for_delivery' => isset($_POST['min_amount_for_delivery'])
                                    ? (float) str_replace(',', '', $_POST['min_amount_for_delivery']) : 0,
    'contact'                 => $_POST['contact']                 ?? null,
    'email'                   => $_POST['email']                   ?? null,
    'person_in_charge'        => $_POST['person_in_charge']        ?? null,
    'terms'                   => $_POST['terms']                   ?? null,
    'payment_remarks'         => $_POST['payment_remarks']         ?? null,
    'remarks'                 => $_POST['remarks']                 ?? null,
];

$sql = "UPDATE transactions SET
    po_date=:po_date, po_number=:po_number, inv_date=:inv_date, inv_number=:inv_number,
    vendor=:vendor, item=:item, department=:department, department_remarks=:department_remarks,
    unit=:unit, uom=:uom, price=:price, row_remarks=:row_remarks, sst=:sst,
    total_price=:total_price, min_amount_for_delivery=:min_amount_for_delivery,
    contact=:contact, email=:email, person_in_charge=:person_in_charge,
    terms=:terms, payment_remarks=:payment_remarks, remarks=:remarks
    WHERE id=:id";

$stmt = $pdo->prepare($sql);
foreach ($data as $k => $v) $stmt->bindValue(":$k", $v);
$stmt->bindValue(':id', $id, PDO::PARAM_INT);

// Handle optional invoice upload
if (isset($_FILES['invoice_file']) && $_FILES['invoice_file']['error'] === UPLOAD_ERR_OK) {
    $ext = strtolower(pathinfo($_FILES['invoice_file']['name'], PATHINFO_EXTENSION));
    if (in_array($ext, ['pdf','jpg','jpeg','png'])) {
        $dir = __DIR__ . "/uploads/transactions/transaction_{$id}/invoices/";
        if (!is_dir($dir)) mkdir($dir, 0755, true);
        $dest = $dir . "invoice.{$ext}";
        if (move_uploaded_file($_FILES['invoice_file']['tmp_name'], $dest)) {
            $path = "uploads/transactions/transaction_{$id}/invoices/invoice.{$ext}";
            $pdo->prepare("UPDATE transactions SET invoice_path=? WHERE id=?")->execute([$path, $id]);
        }
    }
}

if ($stmt->execute()) {
    echo json_encode(['success' => true]);
} else {
    http_response_code(500);
    echo json_encode(['error' => 'Update failed']);
}
