<?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['account_name'] ?? [];
$acc_type  = $_POST['acc_type'] ?? [];
$acc_categ = $_POST['acc_categ'] ?? [];
$acc_source  = $_POST['acc_source'] ?? [];
$status = $_POST['status'] ?? [];
$pnl = $_POST['pnl'] ?? [];
$bl_sheet = $_POST['bl_sheet'] ?? [];


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, status, PnL, bl_sheet  )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
");

try {

    $pdo->beginTransaction();
    
        $coid = $_SESSION['co_id'];
    for ($i = 0; $i < count($names); $i++) {
       // $coid      = trim($coid[$i] ?? '');
        $name      = trim($names[$i] ?? '');
        $acc_type  = trim($acc_type[$i] ?? '');
        $acc_categ  = trim($acc_categ[$i] ?? '');
        $acc_source   = trim($acc_source[$i] ?? '');
        $status   = trim($status[$i] ?? '');
        $pnl   = trim($pnl[$i] ?? '');
        $bl_sheet   = trim($bl_sheet[$i] ?? '');
        

        // Skip completely empty rows
       

        // Validate required fields
        if ($name === '' || $acc_type === '' || $status === '') {
            throw new Exception("Invalid Capacity on line" . ($i + 1));
        }
        
        // Validate required fields
        if ( $acc_source === '') {
            throw new Exception("Manager does not exist on line" . ($i + 1));
        }

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

    $pdo->commit();

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

} catch (Exception $e) {

    $pdo->rollBack();

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