<?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'];

    // Get current remaining balance and plan details
    $stmt = $connation->prepare("SELECT ip.*, cd.cs_name, cd.cs_mobile, 
                                ip.monthly_installment, ip.total_installments
                                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();
    $result = $stmt->get_result();
    $plan = $result->fetch_assoc();

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

    // Calculate remaining months
    $monthly_installment = $plan['monthly_installment'];
    $remaining_months = ceil($new_balance / $monthly_installment);
    $total_installments = $plan['total_installments'];
    $completed_months = $total_installments - $remaining_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);

    // Update remaining balance in installment_plans
    $stmt2 = $connation->prepare("UPDATE installment_plans SET remaining_balance = ? WHERE plan_id = ?");
    $stmt2->bind_param("di", $new_balance, $plan_id);

    if ($stmt->execute() && $stmt2->execute()) {
        echo "<div class='alert alert-success'>Payment Recorded Successfully!</div>";
        $print_bill = true;
    } else {
        echo "<div class='alert alert-danger'>Error recording payment: " . $stmt->error . "</div>";
    }
}

if ($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;">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>
        <tr>
            <td style="width: 50%; font-size: <?php echo setting_view("bill_font_size"); ?>px;">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;">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;">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;">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>
        <!-- New rows for installment information -->
        <tr>
            <td style="width: 50%; font-size: <?php echo setting_view("bill_font_size"); ?>px;">Monthly Installment</td>
            <td style="width: 50%; font-size: <?php echo setting_view("bill_font_size"); ?>px;" align="right"><?php echo number_format($monthly_installment, 2); ?></td>
        </tr>
        <tr style="font-weight: bold;">
            <td style="width: 50%; font-size: <?php echo setting_view("bill_font_size"); ?>px;">Remaining Months</td>
            <td style="width: 50%; font-size: <?php echo setting_view("bill_font_size"); ?>px;" align="right"><?php echo $remaining_months; ?> of <?php echo $total_installments; ?></td>
        </tr>
        <tr>
            <td style="width: 50%; font-size: <?php echo setting_view("bill_font_size"); ?>px;">Installments Completed</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;">
        Next Payment Due: <?php echo date('M d, Y', strtotime('+1 month')); ?>
    </div>
    
    <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>
    
    <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>