<?php
session_start(['read_and_close' => true]);
require 'db.php';
header('Content-Type: application/json');

/* ==========================
   AUTH CHECK
========================== */
if (!isset($_SESSION['co_id'])) {
    echo json_encode(["status" => "error", "message" => "Unauthorized"]);
    exit;
}

$coid  = $_SESSION['co_id'];

session_write_close();

$names  = $_POST['cust_name'] ?? [];
$status = $_POST['status'] ?? [];

/* Fixed values */
$acc_type   = 'Cash';
$acc_categ  = 'customer';
$entry_form = 'sale';
$acc_source = 'external';
$pnl        = 'none';
$bl_sheet   = 'current assets';

if (empty($names)) {
    echo json_encode(["status" => "error", "message" => "No data received"]);
    exit;
}

$stmt = $pdo->prepare("
    INSERT INTO accounts 
    (co_id, acc_name, acc_type, acc_categ, entry_form, acc_source, status, PnL, bl_sheet)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
");

try {

    $pdo->beginTransaction();

    for ($i = 0; $i < count($names); $i++) {

        $name   = trim($names[$i] ?? '');
        $stat   = trim($status[$i] ?? '');

        if ($name === '' || $stat === '') {
            throw new Exception("Invalid data on line " . ($i + 1));
        }

        $stmt->execute([
            $coid,
            $name,
            $acc_type,
            $acc_categ,
            $entry_form,
            $acc_source,
            $stat,
            $pnl,
            $bl_sheet
        ]);
    }

    $pdo->commit();

    echo json_encode(["status" => "success"]);

} catch (Exception $e) {

    $pdo->rollBack();

    echo json_encode([
        "status" => "error",
        "message" => $e->getMessage()
    ]);
}