<?php
session_start();
require("php_con.php");
require("function.php");

if(!isset($_COOKIE['user_id'])){
    echo "<script>window.location='logout';</script>";
    exit();
}

$print_bill = false;
$print_id = '';

// Handle AJAX search request
if(isset($_POST['action']) && $_POST['action'] == 'search_customer') {
    $search = mysqli_real_escape_string($connation, $_POST["query"]);
    $query = "SELECT cs_id, cs_name, cs_mobile FROM customer_details 
              WHERE cs_name LIKE '%$search%' OR cs_mobile LIKE '%$search%' 
              LIMIT 5";
    
    $result = mysqli_query($connation, $query);
    
    if(mysqli_num_rows($result) > 0) {
        while($row = mysqli_fetch_assoc($result)) {
            echo "<div class='customer_item' data-id='".$row['cs_id']."'>".$row['cs_name']." (".$row['cs_mobile'].")</div>";
        }
    } else {
        echo "<div>No customer found</div>";
    }
    exit;
}


if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['action'])) {
    $plan_id = $_POST['plan_id'];
    $amount_paid = $_POST['amount_paid'];

    // Start transaction
    $connation->begin_transaction();

    try {
        // Get current plan details
        $stmt = $connation->prepare("SELECT 
            ip.plan_id, ip.total_amount, ip.remaining_balance, ip.duration_months, 
            ip.monthly_payment, ip.product_name,
            cd.cs_name, cd.cs_mobile
            FROM installment_plans ip 
            JOIN customer_details cd ON ip.cs_id = cd.cs_id 
            WHERE ip.plan_id = ?");
        $stmt->bind_param("i", $plan_id);
        $stmt->execute();
        $plan = $stmt->get_result()->fetch_assoc();

        if (!$plan) {
            throw new Exception("Plan not found.");
        }

        $current_balance = $plan['remaining_balance'];
        $new_balance = $current_balance - $amount_paid;

        // Get payment history
        $payments_query = $connation->prepare("SELECT COUNT(*) as payment_count
            FROM installment_payments 
            WHERE plan_id = ?");
        $payments_query->bind_param("i", $plan_id);
        $payments_query->execute();
        $payments_data = $payments_query->get_result()->fetch_assoc();

        $completed_months = $payments_data['payment_count'] + 1; // Including current payment
        $remaining_months = $plan['duration_months'] - $completed_months;

        // Generate a unique bill ID
        $print_id = 'INST-' . date('YmdHis') . '-' . $plan_id;

        // Record payment
        $stmt = $connation->prepare("INSERT INTO installment_payments 
            (plan_id, amount_paid, payment_date, remaining_balance) 
            VALUES (?, ?, NOW(), ?)");
        $stmt->bind_param("idd", $plan_id, $amount_paid, $new_balance);
        $stmt->execute();

        // Update remaining balance in installment_plans
        $stmt2 = $connation->prepare("UPDATE installment_plans 
            SET remaining_balance = ?, 
                status = CASE WHEN ? <= 0 THEN 'completed' ELSE 'active' END
            WHERE plan_id = ?");
        $stmt2->bind_param("ddi", $new_balance, $new_balance, $plan_id);
        $stmt2->execute();

        // Commit transaction
        $connation->commit();

        echo "<div class='alert alert-success'>Payment Recorded Successfully!</div>";
        $print_bill = true;

    } catch (Exception $e) {
        // Rollback transaction on error
        $connation->rollback();
        echo "<div class='alert alert-danger'>Error: " . $e->getMessage() . "</div>";
    }
}

if (isset($print_bill) && $print_bill) {
    ?>
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Installment Payment Bill - <?php echo $print_id; ?></title>
    <link href="cus_css.css" rel="stylesheet" type="text/css">
    <style>
        * { font-size: <?php echo setting_view("bill_font_size"); ?>px; }
    </style>
    </head>
    <body style="margin: 0px; padding: 0px;">
    
    <?php if(setting_view("bill_logo_display")==1){ ?>
        <div align="center"><img src="image/bill12.png" style="width: <?php echo setting_view("logo_width"); ?>%; margin-bottom: 5px;"></div>
    <?php } ?>
    <?php if(setting_view("bill_title_display")==1){ ?>
        <div align="center" style="font-weight: bold;font-size: <?php echo setting_view("bill_font_size")+6; ?>px;"><?php echo setting_view("bill_title"); ?></div>
    <?php } ?>
    <?php if(setting_view("bill_address_display")==1){ ?>
        <div align="center" style="white-space: pre-line;"><?php echo setting_view("bill_address"); ?></div>
    <?php } ?>
    <?php if(setting_view("bill_email_display")==1){ ?>
        <div align="center"><?php echo setting_view("bill_email"); ?></div>
    <?php } ?>
    <?php if(setting_view("bill_mobile_display")==1){ ?>
        <div align="center" style="margin-bottom: 5px;"><?php echo setting_view("bill_mobile"); ?></div>
    <?php } ?>
    
    <div style="border-bottom: 1px solid #000000;"></div>
    
    <table style="margin-bottom: 5px; width: 100%;">
    <tbody>
    <tr>
        <td align="left" valign="middle" style="padding-right: 5px; font-size: <?php echo setting_view("bill_font_size"); ?>px;">
            <?php echo (setting_view("bill_lan")==1) ? 'දිනය' : 'Date'; ?>:<br><?php echo date("M d, Y"); ?>
        </td>
        <td align="left" valign="middle" style="padding-right: 5px; font-size: <?php echo setting_view("bill_font_size"); ?>px;">
            <?php echo (setting_view("bill_lan")==1) ? 'වේලාව' : 'Time'; ?>:<br><?php echo date("h:i:s A"); ?>
        </td>
    </tr>
    <tr>
        <td align="left" valign="middle" style="padding-top: 5px; padding-right: 5px; font-size: <?php echo setting_view("bill_font_size"); ?>px;">
            <?php echo (setting_view("bill_lan")==1) ? 'බිල්පත' : 'Invoice'; ?>:<br><?php echo $print_id; ?>
        </td>
        <td align="left" valign="middle" style="padding-top: 5px; padding-right: 5px; font-size: <?php echo setting_view("bill_font_size"); ?>px;">
            <?php echo (setting_view("bill_lan")==1) ? 'අයකැමි' : 'Cashier'; ?>:<br><?php echo $_COOKIE['user_id']; ?>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="left" valign="middle" style="padding-right: 5px; font-size: <?php echo setting_view("bill_font_size"); ?>px;">
            <?php echo (setting_view("bill_lan")==1) ? 'පාරිභෝගික' : 'Customer'; ?>: <?php echo $plan['cs_name']; ?> (<?php echo $plan['cs_mobile']; ?>)
        </td>
    </tr>
    </tbody>
    </table>
    
    <div style="border-bottom: 1px solid #000000;"></div>
    
    <table style="width: 100%;">
    <tbody>
        <tr>
            <td style="width: 50%; font-size: <?php echo setting_view("bill_font_size"); ?>px;">
                <?php echo (setting_view("bill_lan")==1) ? 'භාණ්ඩය' : 'Product'; ?>
            </td>
            <td style="width: 50%; font-size: <?php echo setting_view("bill_font_size"); ?>px;" align="right">
                <?php echo $plan['product_name']; ?>
            </td>
            <tr>
            <td style="width: 50%; font-size: <?php echo setting_view("bill_font_size"); ?>px;"><?php echo (setting_view("bill_lan")==1) ? 'මුළු මුදල' : 'Total Amount'; ?></td>
            <td style="width: 50%; font-size: <?php echo setting_view("bill_font_size"); ?>px;" align="right"><?php echo number_format($plan['total_amount'], 2); ?></td>
        </tr>
        <tr>
            <td style="width: 50%; font-size: <?php echo setting_view("bill_font_size"); ?>px;"><?php echo (setting_view("bill_lan")==1) ? 'පෙර ශේෂය' : 'Previous Balance'; ?></td>
            <td style="width: 50%; font-size: <?php echo setting_view("bill_font_size"); ?>px;" align="right"><?php echo number_format($current_balance, 2); ?></td>
        </tr>
        <tr>
            <td style="width: 50%; font-size: <?php echo setting_view("bill_font_size"); ?>px;"><?php echo (setting_view("bill_lan")==1) ? 'ගෙවූ මුදල' : 'Amount Paid'; ?></td>
            <td style="width: 50%; font-size: <?php echo setting_view("bill_font_size"); ?>px;" align="right"><?php echo number_format($amount_paid, 2); ?></td>
        </tr>
        <tr style="font-weight: bold;">
            <td style="width: 50%; font-size: <?php echo setting_view("bill_font_size")+1; ?>px;"><?php echo (setting_view("bill_lan")==1) ? 'ඉතිරි ශේෂය' : 'Remaining Balance'; ?></td>
            <td style="width: 50%; font-size: <?php echo setting_view("bill_font_size")+1; ?>px;" align="right"><?php echo number_format($new_balance, 2); ?></td>
        </tr>
        <tr>
            <td style="width: 50%; font-size: <?php echo setting_view("bill_font_size"); ?>px;">
                <?php echo (setting_view("bill_lan")==1) ? 'ඉතිරි මාස' : 'Estimated Remaining Months'; ?>
            </td>
            <td style="width: 50%; font-size: <?php echo setting_view("bill_font_size"); ?>px;" align="right">
                <?php echo $remaining_months; ?>
            </td>
        </tr>
        <tr>
            <td style="width: 50%; font-size: <?php echo setting_view("bill_font_size"); ?>px;">
                <?php echo (setting_view("bill_lan")==1) ? 'ගෙවූ වාරික ගණන' : 'Payments Made'; ?>
            </td>
            <td style="width: 50%; font-size: <?php echo setting_view("bill_font_size"); ?>px;" align="right">
                <?php echo $completed_months; ?>
            </td>
        </tr>
    </tbody>
    </table>
    
    <div style="border-bottom: 1px solid #000000; margin-top: 5px; margin-bottom: 5px;"></div>
    
    <div style="font-size: <?php echo setting_view("bill_font_size"); ?>px;">
        <?php echo (setting_view("bill_lan")==1) ? 'ඊළඟ ගෙවීම් දිනය' : 'Next Payment Due'; ?>: 
        <?php echo date('M d, Y', strtotime('+1 month')); ?>
    </div>

    <?php if($new_balance <= 0) { ?>
    <div style="border: 1px dashed #000000; margin: 5px 0px; text-align: center; font-weight: bold; font-size: <?php echo setting_view("bill_font_size")+1; ?>px;">
        <?php echo (setting_view("bill_lan")==1) ? 'සම්පූර්ණයෙන් ගෙවා ඇත' : 'FULLY PAID'; ?>
    </div>
    <?php } ?>
    
    <div style="border-bottom: 1px solid #000000; margin-top: 5px;"></div>
    
    <div class="bill-footer" style="font-size: <?php echo setting_view("bill_font_size")-1; ?>px;">
        <div style="white-space: pre-line; font-style: normal;"><?php echo setting_view("bill_footer_text"); ?></div>
        System powered by Nova POS - 0769146421 / 0777404233
    </div>

    <div style="margin-top: 10px; padding: 5px; font-size: <?php echo setting_view("bill_font_size")-1; ?>px;">
        <div style="text-align: left; margin-bottom: 5px;">Terms & Conditions:</div>
        <div style="text-align: left; margin-left: 10px;">
            1. Late payments will incur additional charges.<br>
            2. Product warranty is valid only with this original receipt.<br>
            3. Please keep this receipt for future reference.
        </div>
    </div>

    <div style="text-align: center; margin-top: 10px; font-size: <?php echo setting_view("bill_font_size")-1; ?>px;">
        <?php echo (setting_view("bill_lan")==1) ? 'ස්තූතියි! නැවත පැමිණෙන්න' : 'Thank You! Come Again'; ?>
    </div>
    
    <script>
    window.onload = function() {
        window.print();
        setTimeout(function() {
            window.location.href = 'record_payment.php';
        }, 1000);
    };
    </script>
    </body>
    </html>
    <?php
    exit();
}

        

require("header.php");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <title>Record Payment</title>
    <style>
        .customer_item {
            cursor: pointer;
            padding: 5px;
        }
        .customer_item:hover {
            background-color: #f0f0f0;
        }
    </style>
</head>
<body>
<?php include 'navbar.php'; ?>
<div class="container mt-5">
    <h2>Record Payment</h2>
    <form action="record_payment.php" method="POST">
        <div class="form-group">
            <label for="customer_search">Search Customer:</label>
            <input type="text" class="form-control" id="customer_search" placeholder="Enter name or phone number">
            <div id="customer_results" class="mt-2"></div>
        </div>
        <div class="form-group">
            <label for="plan">Installment Plan:</label>
            <select class="form-control" id="plan" name="plan_id" required>
                <option value="">Select a plan</option>
            </select>
        </div>
        <div class="form-group">
            <label for="amount">Amount Paid:</label>
            <input type="number" step="0.01" class="form-control" id="amount" name="amount_paid" required>
        </div>
        <button type="submit" class="btn btn-primary">Record Payment</button>
    </form>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(document).ready(function() {
    $('#customer_search').on('input', function() {
        var search = $(this).val();
        if(search != "") {
            $.ajax({
                url: "record_payment.php",
                method: "POST",
                data: {action: "search_customer", query: search},
                success: function(data) {
                    $('#customer_results').html(data);
                }
            });
        } else {
            $('#customer_results').html('');
            $('#plan').html('<option value="">Select a plan</option>');
        }
    });

    $(document).on('click', '.customer_item', function() {
        var customerId = $(this).data('id');
        $('#customer_search').val($(this).text());
        $('#customer_results').html('');

        // Fetch installment plans for the selected customer
        $.ajax({
            url: "get_customer_plans.php",
            method: "POST",
            data: {customer_id: customerId},
            success: function(data) {
                $('#plan').html(data);
            }
        });
    });
});
</script>
</body>
</html>