<?php
declare(strict_types=1);

/**
 * File: /home/jewellersbd/public_html/erp.jewellersbd.com/api/cash/day_close.php
 * POST: account_id, closing_date, calc_balance, physical_count
 */

require_once __DIR__ . '/../../config/db.php';

header('Content-Type: application/json; charset=UTF-8');

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (empty($_SESSION['user_id'])) {
    echo json_encode([
        'success' => false,
        'message' => 'Login করুন।',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$accountId   = (int)($_POST['account_id'] ?? 0);
$closingDate = trim((string)($_POST['closing_date'] ?? date('Y-m-d')));
$calcBalance = round((float)($_POST['calc_balance'] ?? 0), 2);

$physicalRaw = $_POST['physical_count'] ?? null;
$physicalCount = ($physicalRaw !== null && $physicalRaw !== '')
    ? round((float)$physicalRaw, 2)
    : null;

$userId = (int)$_SESSION['user_id'];

if ($accountId <= 0) {
    echo json_encode([
        'success' => false,
        'message' => 'Account নির্বাচন করুন।',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$dateCheck = DateTime::createFromFormat('Y-m-d', $closingDate);
if (
    !$dateCheck
    || $dateCheck->format('Y-m-d') !== $closingDate
) {
    echo json_encode([
        'success' => false,
        'message' => 'সঠিক closing date দিন।',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    /*
    |--------------------------------------------------------------------------
    | Cash account যাচাই
    |--------------------------------------------------------------------------
    */

    $accountStmt = $pdo->prepare(
        'SELECT id, opening_balance
         FROM cash_accounts
         WHERE id = ?
           AND deleted_at IS NULL
         LIMIT 1'
    );
    $accountStmt->execute([$accountId]);
    $account = $accountStmt->fetch(PDO::FETCH_ASSOC);

    if (!$account) {
        echo json_encode([
            'success' => false,
            'message' => 'Cash account পাওয়া যায়নি।',
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    /*
    |--------------------------------------------------------------------------
    | একই তারিখে account আগে close হয়েছে কিনা
    |--------------------------------------------------------------------------
    */

    $checkStmt = $pdo->prepare(
        'SELECT id
         FROM cash_daily_closing
         WHERE cash_account_id = ?
           AND closing_date = ?
         LIMIT 1'
    );
    $checkStmt->execute([$accountId, $closingDate]);

    if ($checkStmt->fetchColumn()) {
        echo json_encode([
            'success' => false,
            'message' => 'এই account আজকের জন্য আগেই বন্ধ করা হয়েছে।',
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    /*
    |--------------------------------------------------------------------------
    | Closing date-এর IN / OUT হিসাব
    |--------------------------------------------------------------------------
    */

    $transactionStmt = $pdo->prepare(
        "SELECT
            COALESCE(SUM(
                CASE
                    WHEN direction = 'IN' AND is_deleted = 0
                    THEN amount ELSE 0
                END
            ), 0) AS total_in,
            COALESCE(SUM(
                CASE
                    WHEN direction = 'OUT' AND is_deleted = 0
                    THEN amount ELSE 0
                END
            ), 0) AS total_out,
            SUM(
                CASE
                    WHEN is_deleted = 0 THEN 1 ELSE 0
                END
            ) AS transaction_count
         FROM cash_transactions
         WHERE cash_account_id = ?
           AND transaction_date = ?"
    );
    $transactionStmt->execute([$accountId, $closingDate]);

    $day = $transactionStmt->fetch(PDO::FETCH_ASSOC) ?: [];

    $totalIn = round((float)($day['total_in'] ?? 0), 2);
    $totalOut = round((float)($day['total_out'] ?? 0), 2);
    $transactionCount = (int)($day['transaction_count'] ?? 0);

    /*
    |--------------------------------------------------------------------------
    | Opening balance
    |--------------------------------------------------------------------------
    | আগে closing থাকলে সর্বশেষ closing balance।
    | না থাকলে cash account-এর opening balance।
    */

    $previousStmt = $pdo->prepare(
        'SELECT calculated_balance
         FROM cash_daily_closing
         WHERE cash_account_id = ?
           AND closing_date < ?
         ORDER BY closing_date DESC
         LIMIT 1'
    );
    $previousStmt->execute([$accountId, $closingDate]);
    $previousClosing = $previousStmt->fetchColumn();

    $openingBalance = ($previousClosing !== false)
        ? round((float)$previousClosing, 2)
        : round((float)$account['opening_balance'], 2);

    $difference = ($physicalCount !== null)
        ? round($physicalCount - $calcBalance, 2)
        : null;

    /*
    |--------------------------------------------------------------------------
    | Day closing save
    |--------------------------------------------------------------------------
    */

    $insertStmt = $pdo->prepare(
        'INSERT INTO cash_daily_closing
            (
                closing_date,
                cash_account_id,
                opening_balance,
                total_in,
                total_out,
                calculated_balance,
                physical_count,
                difference,
                transaction_count,
                closed_by,
                closed_at
            )
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())'
    );

    $insertStmt->execute([
        $closingDate,
        $accountId,
        $openingBalance,
        $totalIn,
        $totalOut,
        $calcBalance,
        $physicalCount,
        $difference,
        $transactionCount,
        $userId,
    ]);

    $message = date('d M Y', strtotime($closingDate))
        . ' — সফলভাবে বন্ধ হয়েছে।';

    if ($difference !== null) {
        if ($difference == 0.0) {
            $message .= ' হিসাব মিলেছে ✅';
        } elseif ($difference > 0) {
            $message .= ' উদ্বৃত্ত: +৳'
                . number_format($difference, 2);
        } else {
            $message .= ' ঘাটতি: ৳'
                . number_format(abs($difference), 2)
                . ' ⚠️';
        }
    }

    echo json_encode([
        'success'    => true,
        'message'    => $message,
        'total_in'   => $totalIn,
        'total_out'  => $totalOut,
        'calc_bal'   => $calcBalance,
        'physical'   => $physicalCount,
        'difference' => $difference,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

} catch (Throwable $e) {
    error_log('Cash day close failed: ' . $e->getMessage());

    echo json_encode([
        'success' => false,
        'message' => 'Day close সংরক্ষণ করা যায়নি।',
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
