<?php
include 'includes/config.php';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_receive'])) {
    try {
        $user_id = $_POST['customer_id'] ?? null;
        $amount = $_POST['receive_amount'] ?? null;
        $bank_id = $_POST['bank_id'] ?? null;
        $payment_status = 'Received';
        $date_deposit = $_POST['date_deposit'] ?? null;

        if (!$user_id || !$amount || !$bank_id || !$date_deposit) {
            throw new Exception('Missing required fields');
        }

       
        $insertQuery = "INSERT INTO cash_deposit (bank_id, user_id, amount, payment_status, date_deposit) 
                        VALUES (:bank_id, :user_id, :amount, :payment_status, :date_deposit)";
        $stmt = $conn->prepare($insertQuery);
        $stmt->bindParam(':bank_id', $bank_id);
        $stmt->bindParam(':user_id', $user_id);
        $stmt->bindParam(':amount', $amount);
        $stmt->bindParam(':payment_status', $payment_status);
        $stmt->bindParam(':date_deposit', $date_deposit);
        $stmt->execute();

        // Fetch customer data for balance
               $query = "SELECT 
                c.id AS customer_id, 
                c.name AS customer_name,
                COALESCE(s.total_sales_amount, 0) AS total_sales_amount,
                c.opening_balance,
                COALESCE(cd.total_deposit, 0) AS total_deposit,
                (SELECT COALESCE(SUM(amount), 0) FROM customer_bill_manual WHERE user_id = c.id) AS total_billed_amount
            FROM 
                contacts c
            LEFT JOIN 
                (SELECT customer_id, SUM(total_amount) AS total_sales_amount 
                 FROM stock_sale 
                 GROUP BY customer_id) s ON c.id = s.customer_id
            LEFT JOIN 
                (SELECT user_id, SUM(amount) AS total_deposit 
                 FROM cash_deposit 
                 GROUP BY user_id) cd ON c.id = cd.user_id  
            WHERE c.id = :user_id AND c.type = 'customer'
            GROUP BY 
                c.id, c.name, c.opening_balance, s.total_sales_amount, cd.total_deposit";

        $stmt = $conn->prepare($query);
        $stmt->bindParam(':user_id', $user_id);
        $stmt->execute();
        $customer = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($customer) {
            $remaining_balance = ($customer['total_sales_amount'] - $customer['total_deposit']) + $customer['opening_balance'];
            $final_balance = $remaining_balance + $customer['total_billed_amount'];
        } else {
            $final_balance = 0;
        }

        echo json_encode([
            'success' => true,
            'user_id' => $user_id,
            'amount' => $amount,
            'final_balance' => $final_balance
        ]);
        exit;

    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => $e->getMessage()
        ]);
        exit;
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}
