<?php
// add_transaction.php — handles POST to insert a new transaction

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

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

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

// Collect and sanitise
$po_date      = $_POST['po_date']      ?? '';
$po_number    = $_POST['po_number']    ?? '';
$inv_date     = $_POST['inv_date']     ?? '';
$inv_number   = $_POST['inv_number']   ?? '';
$vendor       = $_POST['vendor']       ?? '';
$item         = $_POST['item']         ?? '';
$department   = $_POST['department']   ?? '';
$department_remarks      = $_POST['department_remarks']      ?? '';
$uom          = $_POST['uom']          ?? '';
$row_remarks  = $_POST['row_remarks']  ?? '';
$contact      = $_POST['contact']      ?? '';
$email        = $_POST['email']        ?? '';
$person_in_charge        = $_POST['person_in_charge']        ?? '';
$terms        = $_POST['terms']        ?? '';
$payment_remarks         = $_POST['payment_remarks']         ?? '';
$remarks      = $_POST['remarks']      ?? '';

$unit                    = isset($_POST['unit'])                    ? (float) str_replace(',', '', $_POST['unit'])                    : 0;
$price                   = isset($_POST['price'])                   ? (float) str_replace(',', '', $_POST['price'])                   : 0;
$total_price             = isset($_POST['total_price'])             ? (float) str_replace(',', '', $_POST['total_price'])             : 0;
$sst                     = isset($_POST['sst'])                     ? (float) str_replace(',', '', $_POST['sst'])                     : 0;
$min_amount_for_delivery = isset($_POST['min_amount_for_delivery']) ? (float) str_replace(',', '', $_POST['min_amount_for_delivery']) : 0;

// Insert
$stmt = $pdo->prepare("
    INSERT INTO transactions (
        po_date, po_number, inv_date, inv_number, vendor, item, department, department_remarks,
        unit, uom, price, row_remarks, sst, total_price, min_amount_for_delivery,
        contact, email, person_in_charge, terms, payment_remarks, remarks
    ) VALUES (
        :po_date, :po_number, :inv_date, :inv_number, :vendor, :item, :department, :department_remarks,
        :unit, :uom, :price, :row_remarks, :sst, :total_price, :min_amount_for_delivery,
        :contact, :email, :person_in_charge, :terms, :payment_remarks, :remarks
    )
");
$stmt->execute([
    ':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,
]);

$transactionId = $pdo->lastInsertId();

// Handle invoice upload(s) — supports multiple files
if (isset($_FILES['invoice_file']) && is_array($_FILES['invoice_file']['name'])) {
    $uploadDir = __DIR__ . "/uploads/transactions/transaction_{$transactionId}/invoices/";
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
    $allowed = ['pdf', 'jpg', 'jpeg', 'png'];
    $count = count($_FILES['invoice_file']['name']);
    for ($i = 0; $i < $count; $i++) {
        if ($_FILES['invoice_file']['error'][$i] !== UPLOAD_ERR_OK) continue;
        $origName = $_FILES['invoice_file']['name'][$i];
        $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
        if (!in_array($ext, $allowed)) continue;
        // Sanitise filename and avoid collisions
        $safeName = preg_replace('/[^a-zA-Z0-9._-]/', '_', $origName);
        $dest = $uploadDir . $safeName;
        // Avoid overwriting: append index if needed
        if (file_exists($dest)) $dest = $uploadDir . pathinfo($safeName, PATHINFO_FILENAME) . "_{$i}." . $ext;
        move_uploaded_file($_FILES['invoice_file']['tmp_name'][$i], $dest);
    }
    // Store path of first file in invoice_path column for backward compatibility
    $first = scandir($uploadDir);
    $first = array_values(array_filter($first, fn($f) => !in_array($f, ['.','..'])));
    if (!empty($first)) {
        $invoice_path = "uploads/transactions/transaction_{$transactionId}/invoices/" . $first[0];
        $pdo->prepare("UPDATE transactions SET invoice_path = :p WHERE id = :id")
            ->execute([':p' => $invoice_path, ':id' => $transactionId]);
    }
}

echo json_encode(['success' => true, 'transactionId' => $transactionId]);
