<?php
session_start();
if (!isset($_SESSION['username'])) {
    header('Location: /manage/index.php');
    exit;
}

require_once '../includes/db.php';

$bill_number = $_GET['bill'] ?? '';
if (!$bill_number) die("Invalid or missing bill number.");

// Fetch bill & customer
$stmt = $pdo->prepare("SELECT b.*, c.name, c.contact_number FROM bills b JOIN customers c ON b.customer_id = c.customer_id WHERE b.bill_number = ?");
$stmt->execute([$bill_number]);
$bill_data = $stmt->fetch();
if (!$bill_data) die("Bill not found.");

$customer_data = [
    'name' => $bill_data['name'],
    'contact' => $bill_data['contact_number'],
    'bill_number' => $bill_data['bill_number'],
    'in_date' => $bill_data['in_date']
];

$bill_id = $bill_data['bill_id'];
$pickup_delivery_charge = $bill_data['pickup_delivery_charge'] ?? 0; // Added Pickup/Delivery Charge

// Fetch existing advance payment (if any)
$stmtPayment = $pdo->prepare("SELECT amount FROM payments WHERE bill_id = ? AND reference = 'Advance Payment' LIMIT 1");
$stmtPayment->execute([$bill_id]);
$advance_payment = $stmtPayment->fetchColumn() ?? 0; // Default to 0 if no advance payment exists

// Save delivery date or redirect
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] === 'close') {
    $required_date = $_POST['required_date'] ?? null;
    $advance_payment_input = $_POST['advance_payment'] ?? 0;  // Get the advance payment amount (default to 0 if not provided)
    $pickup_delivery_input = $_POST['pickup_delivery_charge'] ?? 0; // Get the pickup/delivery charge

    // Validate the payment
    if ($required_date && preg_match('/^\d{4}-\d{2}-\d{2}$/', $required_date)) {
        $updateStmt = $pdo->prepare("UPDATE bills SET required_date = ?, pickup_delivery_charge = ? WHERE bill_id = ?");
        $updateStmt->execute([$required_date, $pickup_delivery_input, $bill_id]);

        // If there is a new advance payment and no payment has been made already, insert it into the payments table
        if ($advance_payment_input > 0 && $advance_payment == 0) {
            $stmtInsertPayment = $pdo->prepare("INSERT INTO payments (bill_id, amount, created_at, payment_date, method, reference) 
                                               VALUES (?, ?, NOW(), ?, ?, ?)");
            // Assuming cash method and using the current date as the payment date
            $stmtInsertPayment->execute([$bill_id, $advance_payment_input, date('Y-m-d'), 'Advance', 'Advance Payment']);
        }
    }
    echo "<script>
        window.location.href='/pages/invoice.php?bill=$bill_number';
    </script>";
    exit;
}

// Get job types
$job_types_stmt = $pdo->query("SELECT * FROM job_types ORDER BY job_name ASC");
$job_types_raw = $job_types_stmt->fetchAll(PDO::FETCH_ASSOC);

// Group job types by category
$job_categories = [];
foreach ($job_types_raw as $jt) {
    $parts = explode(" - ", $jt['job_name'], 2);
    $category = trim($parts[0] ?? 'Misc');
    $name = trim($parts[1] ?? $jt['job_name']);
    $job_categories[$category][] = [
        'job_type_id' => $jt['job_type_id'],
        'name' => $name,
        'rate' => $jt['rate']
    ];
}

// Fetch current jobs
$stmt = $pdo->prepare("SELECT j.*, t.job_name FROM jobs j JOIN job_types t ON j.job_type_id = t.job_type_id WHERE j.bill_id = ?");
$stmt->execute([$bill_id]);
$jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);

$grouped_jobs = [];

foreach ($jobs as $job) {
    $parts = explode(' - ', $job['job_name'], 2);
    $category = trim($parts[0] ?? 'Other');
    $job_name = trim($parts[1] ?? $job['job_name']);

    $grouped_jobs[$category][] = [
        'name' => $job_name,
        'rate' => $job['rate'],
        'qty' => $job['qty'],
        'total' => $job['total']
    ];
}

$grand_total = 0;
foreach ($jobs as $job) {
    $grand_total += floatval($job['total']);
}

// Subtract the advance payment and add the pickup/delivery charge from the grand total
$adjusted_total = $grand_total - $advance_payment + $pickup_delivery_charge;
?>

<?php include '../includes/header.php'; ?>

<h2>Add Jobs - Bill #<?= htmlspecialchars($bill_number) ?></h2>

<section class="customer-details-inline">
    <strong>Name:</strong> <?= htmlspecialchars($customer_data['name']) ?> &nbsp;|&nbsp;
    <strong>Contact:</strong> <?= htmlspecialchars($customer_data['contact']) ?> &nbsp;|&nbsp;
    <strong>In Date:</strong> <?= htmlspecialchars($customer_data['in_date']) ?>
</section>

<div class="job-main-container">
    <div class="job-categories-side">
        <h3>Job Categories</h3>
        <?php foreach ($job_categories as $category => $jobs_list): ?>
            <div class="job-category">
                <button type="button" class="category-toggle" onclick="toggleCategory(this)">
                    <?= htmlspecialchars($category) ?>
                </button>
                <div class="job-buttons-grid category-content" style="display: none;">
                    <?php foreach ($jobs_list as $job): ?>
                        <button class="job-button"
                            onclick="openJobModal(<?= $job['job_type_id'] ?>, '<?= htmlspecialchars($category . ' - ' . $job['name']) ?>', <?= $job['rate'] ?>)">
                            <?= htmlspecialchars($job['name']) ?><br><small>Rs. <?= number_format($job['rate'], 2) ?></small>
                        </button>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <div class="current-bill-side">
        <h3>Current Bill Jobs</h3>
        <?php if ($jobs): ?>
            <table>
                <thead>
                    <tr>
                        <th>Job</th>
                        <th>Rate</th>
                        <th>Qty</th>
                        <th>Total</th>
                        <th>Remove</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($jobs as $job): ?>
                    <tr id="job-<?= $job['job_id'] ?>">
                        <td><?= htmlspecialchars($job['job_name']) ?></td>
                        <td>Rs. <?= number_format($job['rate'], 2) ?></td>
                        <td><?= $job['qty'] ?></td>
                        <td>Rs. <?= number_format($job['total'], 2) ?></td>
                        <td><span class="delete-job" onclick="removeJob(<?= $job['job_id'] ?>)">&#10006;</span></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <div><strong>Grand Total:</strong> Rs. <?= number_format($grand_total, 2) ?></div>
            
            <div><strong>Advance Payment:</strong> Rs. <?= number_format($advance_payment, 2) ?></div>
            <div><strong>Pickup/Delivery Charge:</strong> Rs. <?= number_format($pickup_delivery_charge, 2) ?></div>
            <div><strong>Due Total (after advance):</strong> Rs. <?= number_format($adjusted_total, 2) ?></div>

            <section style="margin-top: 20px;">
                <h3>Invoice by Section</h3>
                <?php foreach ($grouped_jobs as $section => $items): ?>
                    <h4><?= htmlspecialchars($section) ?></h4>
                    <table>
                        <thead>
                            <tr>
                                <th>Item</th>
                                <th>Qty</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($items as $item): ?>
                                <tr>
                                    <td><?= htmlspecialchars($item['name']) ?></td>
                                    <td><?= $item['qty'] ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <br>
                <?php endforeach; ?>
            </section>
        <?php else: ?>
            <p>No jobs added yet.</p>
        <?php endif; ?>
    </div>
</div>

<section style="margin-top: 20px;">
    <h3>Delivery Date</h3>
    <form method="POST">
        <?php
        $default_required_date = $bill_data['required_date'] ?? date('Y-m-d', strtotime($bill_data['in_date'] . ' +5 days'));
        ?>
        <input type="date" name="required_date" value="<?= htmlspecialchars($default_required_date) ?>" class="date-input" />

        <?php if ($advance_payment == 0): // Only show if no advance payment is made ?>
            <label for="advance_payment">Advance Payment (Rs.)</label>
            <input type="number" name="advance_payment" id="advance_payment" min="0" value="0" />
        <?php endif; ?>

        <label for="pickup_delivery_charge">Pickup/Delivery Charge (Rs.)</label>
        <input type="number" name="pickup_delivery_charge" id="pickup_delivery_charge" min="0" value="<?= number_format($pickup_delivery_charge, 2) ?>" />

        <button type="submit" name="action" value="close">Save Bill</button>
    </form>
</section>

<!-- Modal -->
<div id="jobModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeModal()">&times;</span>
        <h3 id="modalTitle">Add Job</h3>
        <form id="jobForm">
            <input type="hidden" name="job_type_id" id="modal_job_type_id">
            <input type="hidden" name="action" value="ajax_add_job">
            <input type="hidden" name="bill_id" value="<?= $bill_id ?>">

            <label>Rate (Rs.)</label>
            <input type="text" name="rate" id="modal_rate" onclick="setActiveInput('modal_rate')">

            <label>Quantity</label>
            <input type="text" name="qty" id="modal_qty" onclick="setActiveInput('modal_qty')">

            <div class="calculator">
                <?php foreach ([1,2,3,4,5,6,7,8,9,0,'.','C'] as $key): ?>
                    <button type="button" onclick="handleKeypad('<?= $key ?>')"><?= $key ?></button>
                <?php endforeach; ?>
            </div>

            <button type="submit" class="add-btn">➕ Add to Bill</button>
        </form>
    </div>
</div>

<script>
let activeInput = null;

function openJobModal(id, name, rate) {
    document.getElementById('modalTitle').innerText = name;
    document.getElementById('modal_job_type_id').value = id;
    document.getElementById('modal_rate').value = rate.toFixed(2);
    document.getElementById('modal_qty').value = '';
    setActiveInput('modal_qty');
    document.getElementById('jobModal').style.display = 'flex';
}

function closeModal() {
    document.getElementById('jobModal').style.display = 'none';
    activeInput = null;
}

function setActiveInput(fieldId) {
    activeInput = document.getElementById(fieldId);
}

function handleKeypad(value) {
    if (!activeInput) return;
    if (value === 'C') {
        activeInput.value = '';
    } else {
        activeInput.value += value;
    }
}

function toggleCategory(button) {
    const content = button.nextElementSibling;
    const category = button.innerText;

    // Check if the category is already open
    const isOpen = content.style.display === 'block';

    if (isOpen) {
        // If it's open, close it
        content.style.display = 'none';
        // Remove from localStorage
        localStorage.setItem(category, 'closed');
    } else {
        // If it's closed, open it
        content.style.display = 'block';
        // Store the open category in localStorage
        localStorage.setItem(category, 'open');
    }
}

// Preserve open categories after page reload
window.onload = function() {
    const categories = document.querySelectorAll('.category-toggle');
    categories.forEach(categoryButton => {
        const category = categoryButton.innerText;
        const categoryState = localStorage.getItem(category);
        
        // Check if the category state is stored as "open"
        if (categoryState === 'open') {
            categoryButton.nextElementSibling.style.display = 'block';  // Open category
        } else {
            categoryButton.nextElementSibling.style.display = 'none';  // Close category
        }
    });
};

function removeJob(jobId) {
    if (confirm('Are you sure you want to remove this job?')) {
        fetch(`ajax_remove_job.php?job_id=${jobId}`, {
            method: 'GET'
        })
        .then(res => {
            if (!res.ok) {
                throw new Error('Failed to fetch: ' + res.statusText);
            }
            return res.text();
        })
        .then(data => {
            try {
                const jsonData = JSON.parse(data);
                if (jsonData.success) {
                    const row = document.getElementById('job-' + jobId);
                    row.remove();
                } else {
                    alert(jsonData.error || 'Error removing job');
                }
            } catch (e) {
                alert('Error parsing response: ' + e.message);
            }
        })
        .catch(err => alert('Error: ' + err));
    }
}

document.getElementById('jobForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    fetch('ajax_add_job.php', {
        method: 'POST',
        body: formData
    }).then(res => res.text()).then(data => {
        if (data.includes('success')) {
            closeModal();
            location.reload();  // This will refresh the page but preserve open categories
        } else {
            alert(data);
        }
    }).catch(err => alert('Error: ' + err));
});
</script>

<style>
body {
    font-family: 'Segoe UI', sans-serif;
}

.job-main-container {
    display: flex;
    gap: 30px;
    flex-wrap: wrap;
    margin-top: 20px;
}

.job-categories-side,
.current-bill-side {
    flex: 1 1 45%;
    min-width: 300px;
}

.customer-details-inline {
    margin: 15px 0;
    font-size: 14px;
    padding: 8px;
    background: #f8f9fa;
    border: 1px solid #ddd;
    border-radius: 6px;
}

/* POS Style Calculator */
.calculator {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
    margin-top: 15px;
}

.calculator button {
    padding: 15px;
    font-size: 18px;
    font-weight: bold;
    border: none;
    border-radius: 8px;
    background-color: #007bff;
    color: white;
    cursor: pointer;
    transition: background-color 0.2s;
}

.calculator button:hover {
    background-color: #0056b3;
}

.calculator button:active {
    background-color: #00408d;
}

/* Modal Styles */
.modal {
    display: none;
    position: fixed;
    z-index: 999;
    left: 0; top: 0;
    width: 100%; height: 100%;
    background-color: rgba(0, 0, 0, 0.6);
    justify-content: center;
    align-items: center;
}

.modal-content {
    background-color: #fff;
    padding: 30px;
    border-radius: 12px;
    max-width: 400px;
    width: 90%;
    box-shadow: 0 0 20px rgba(0,0,0,0.2);
    animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
    from { opacity: 0; transform: scale(0.9); }
    to { opacity: 1; transform: scale(1); }
}

.modal-content label {
    display: block;
    margin-top: 10px;
    font-weight: 600;
}

.modal-content input {
    width: 100%;
    padding: 10px;
    font-size: 16px;
    margin-top: 5px;
    border: 1px solid #ccc;
    border-radius: 6px;
}

.add-btn {
    margin-top: 15px;
    padding: 12px;
    width: 100%;
    font-size: 16px;
    font-weight: bold;
    background-color: #28a745;
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    transition: background-color 0.2s;
}

.add-btn:hover {
    background-color: #218838;
}

.add-btn:active {
    background-color: #1c6e30;
}

.close {
    float: right;
    font-size: 22px;
    font-weight: bold;
    cursor: pointer;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .job-main-container {
        flex-direction: column;
    }

    .job-categories-side,
    .current-bill-side {
        flex: 1 1 100%;
    }

    .customer-details-inline {
        font-size: 13px;
        line-height: 1.6;
    }
    
    .date-input {
        width: 25%;
        min-width: 180px;
        padding: 10px;
        font-size: 16px;
        border: 1px solid #ccc;
        border-radius: 6px;
    }

    h4 {
        margin-top: 20px;
        font-size: 18px;
        color: #333;
    }
}
</style>

<?php include '../includes/footer.php'; ?>
