<?php
date_default_timezone_set('Asia/Colombo');
session_start();
require_once("connectioni.php");

header('Content-Type: text/html; charset=utf-8');

if ($_SESSION["CURRENT_USER"] == "") {
    echo "Please Login Again !!!";
    exit();
}

if ($_SESSION["dev"] == "") {
    echo "Invalid User Session";
    exit();
}

$Command = $_REQUEST['Command'];

// ============================================
// ADD PAYMENT
// ============================================
if ($Command == "add_payment") {
    $invno = mysqli_real_escape_string($GLOBALS['dbinv'], $_REQUEST['invno']);
    $tmpno = mysqli_real_escape_string($GLOBALS['dbinv'], $_REQUEST['tmpno']);
    $payment_type = mysqli_real_escape_string($GLOBALS['dbinv'], $_REQUEST['payment_type']);
    $payment_amount = mysqli_real_escape_string($GLOBALS['dbinv'], $_REQUEST['payment_amount']);
    $payment_number = mysqli_real_escape_string($GLOBALS['dbinv'], $_REQUEST['payment_number']);
    $payment_date = mysqli_real_escape_string($GLOBALS['dbinv'], $_REQUEST['payment_date']);
    $payment_remark = mysqli_real_escape_string($GLOBALS['dbinv'], $_REQUEST['payment_remark']);
    $created_user = $_SESSION["CURRENT_USER"];
    
    // Validation
    if (empty($payment_type)) {
        echo "Payment type is required!";
        exit();
    }
    
    if (empty($payment_amount) || $payment_amount <= 0) {
        echo "Valid payment amount is required!";
        exit();
    }
    
    if (empty($invno)) {
        echo "Invoice number is required!";
        exit();
    }
    
    // Insert payment
    $sql_insert = "INSERT INTO tem_inv_payment 
                   (invno, tmpno, payment_type, amount, cheque_no, card_no, cheque_date, remarks, created_user, created_date) 
                   VALUES 
                   ('$invno', '$tmpno', '$payment_type', '$payment_amount', '$payment_number', '$payment_number', '$payment_date', '$payment_remark', '$created_user', NOW())";
    
    $result_insert = mysqli_query($GLOBALS['dbinv'], $sql_insert);
    
    if ($result_insert) {
        echo "SUCCESS - Payment added successfully!";
    } else {
        echo "Error: " . mysqli_error($GLOBALS['dbinv']);
    }
}

// ============================================
// LOAD PAYMENT LIST
// ============================================
if ($Command == "load_payment_list") {
    $invno = mysqli_real_escape_string($GLOBALS['dbinv'], $_REQUEST['invno']);
    $tmpno = mysqli_real_escape_string($GLOBALS['dbinv'], $_REQUEST['tmpno']);
    
    if (empty($invno)) {
        echo "";
        exit();
    }
    
    $sql_payment = "SELECT * FROM tem_inv_payment 
                    WHERE invno = '$invno' 
                    ORDER BY id ASC";
    
    $result_payment = mysqli_query($GLOBALS['dbinv'], $sql_payment);
    
    $count = 1;
    $total_amount = 0;
    
    if (mysqli_num_rows($result_payment) > 0) {
        while ($row_payment = mysqli_fetch_array($result_payment)) {
            $total_amount += $row_payment['amount'];
            
            echo "<tr class='linehover'>";
            echo "<td>" . $count . "</td>";
            echo "<td>" . htmlspecialchars($row_payment['payment_type']) . "</td>";
            echo "<td style='text-align:right;'>" . number_format($row_payment['amount'], 2) . "</td>";
            echo "<td>" . htmlspecialchars($row_payment['cheque_no']) . "</td>";
            echo "<td>" . ($row_payment['cheque_date'] != '0000-00-00' ? date('Y-m-d', strtotime($row_payment['cheque_date'])) : '') . "</td>";
            echo "<td>" . htmlspecialchars($row_payment['remarks']) . "</td>";
            echo "<td style='text-align:center;'>";
            echo "<button type='button' class='btn btn-danger btn-xs' onclick='delete_payment(" . $row_payment['id'] . ");'>";
            echo "<span class='fa fa-trash'></span>";
            echo "</button>";
            echo "</td>";
            echo "</tr>";
            
            $count++;
        }
        
        // Total row
        echo "<tr style='background-color:#d8deed; font-weight:bold;'>";
        echo "<td colspan='2' style='text-align:right;'>TOTAL:</td>";
        echo "<td style='text-align:right;'>" . number_format($total_amount, 2) . "</td>";
        echo "<td colspan='4'></td>";
        echo "</tr>";
    } else {
        echo "<tr><td colspan='7' style='text-align:center;'>No payments added yet</td></tr>";
    }
}

// ============================================
// DELETE PAYMENT
// ============================================
if ($Command == "delete_payment") {
    $payment_id = mysqli_real_escape_string($GLOBALS['dbinv'], $_REQUEST['payment_id']);
    $invno = mysqli_real_escape_string($GLOBALS['dbinv'], $_REQUEST['invno']);
    $tmpno = mysqli_real_escape_string($GLOBALS['dbinv'], $_REQUEST['tmpno']);
    
    if (empty($payment_id)) {
        echo "Payment ID is required!";
        exit();
    }
    
    $sql_delete = "DELETE FROM tem_inv_payment WHERE id = '$payment_id'";
    $result_delete = mysqli_query($GLOBALS['dbinv'], $sql_delete);
    
    if ($result_delete) {
        echo "SUCCESS - Payment deleted successfully!";
    } else {
        echo "Error: " . mysqli_error($GLOBALS['dbinv']);
    }
}

// ============================================
// GET TOTAL PAYMENT AMOUNT
// ============================================
if ($Command == "get_total_payment") {
    $invno = mysqli_real_escape_string($GLOBALS['dbinv'], $_REQUEST['invno']);
    
    if (empty($invno)) {
        echo "0.00";
        exit();
    }
    
    $sql_total = "SELECT SUM(amount) as total_payment FROM tem_inv_payment WHERE invno = '$invno'";
    $result_total = mysqli_query($GLOBALS['dbinv'], $sql_total);
    
    if ($row_total = mysqli_fetch_array($result_total)) {
        echo number_format($row_total['total_payment'], 2);
    } else {
        echo "0.00";
    }
}

// ============================================
// SAVE PAYMENT TO PERMANENT TABLE (called during invoice save)
// ============================================
if ($Command == "save_payment_permanent") {
    $invno = mysqli_real_escape_string($GLOBALS['dbinv'], $_REQUEST['invno']);
    $tmpno = mysqli_real_escape_string($GLOBALS['dbinv'], $_REQUEST['tmpno']);
    
    if (empty($invno)) {
        echo "Invoice number is required!";
        exit();
    }
    
    // Copy from temporary table to permanent table (if you have a permanent table)
    // For now, we'll just update the invno in tem_inv_payment table
    
    $sql_update = "UPDATE tem_inv_payment SET invno = '$invno' WHERE tmpno = '$tmpno'";
    $result_update = mysqli_query($GLOBALS['dbinv'], $sql_update);
    
    if ($result_update) {
        echo "SUCCESS - Payments saved!";
    } else {
        echo "Error: " . mysqli_error($GLOBALS['dbinv']);
    }
}

?>
