<?php
ob_start();
include('authentication.php');
include('includes/header.php');
include('includes/navbar.php');
include('dbcon.php');

$client_id = $_GET['client_id'] ?? 0;

// Fetch Client Info
$client = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM tbl_client WHERE Id='$client_id'"));

// Payment Summary
$payment_summary = mysqli_fetch_assoc(mysqli_query($conn, "
    SELECT 
        SUM(paid_amount) AS total_paid,
        MAX(due_date) AS last_due_date
    FROM tbl_payment 
    WHERE client_Id='$client_id'
"));

// *********** PAYMENT CALCULATION ***********
$base_amount = floatval($client['total_amount']);
$gst_amount = floatval($client['gst_amount']);

$grand_total = $base_amount + $gst_amount;

$total_paid = floatval($payment_summary['total_paid'] ?? 0);
$balance = $grand_total - $total_paid;

// Fetch Payment History
$payments = mysqli_query($conn, "SELECT * FROM tbl_payment WHERE client_Id='$client_id' ORDER BY payment_date DESC");


// Fetch Pending Work
$pending_works = mysqli_query($conn, "SELECT * FROM tbl_pending_work WHERE client_id='$client_id' ORDER BY due_date ASC");

// // Fetch Uploaded Documents
// $documents = mysqli_query($conn, "SELECT * FROM  WHERE client_id='$client_id' ORDER BY id DESC");


?>

<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">


<div class="container-fluid" style="color: black; font-size:large">

    <!-- *************************** CLIENT + SERVICE DETAILS SIDE BY SIDE *************************** -->

    <!-- LEFT SIDE: CLIENT DETAILS -->
    <div class="card shadow mb-4">
        <div class="card-header bg-info text-white">
            <h4>Client Details</h4>
        </div>
        <div class="card-body">
            <p><strong>Name:</strong> <?= $client['cust_name']; ?></p>
            <p><strong>Phone:</strong> <?= $client['cust_phone']; ?></p>
            <p><strong>Email:</strong> <?= $client['cust_email']; ?></p>
            <p><strong>Address:</strong> <?= $client['cust_address']; ?></p>
            <button onclick="window.location.href='update-client.php?client_id=<?= $client['id']; ?>'" class="btn btn-success btn-sm mt-2 mr-3" style="width: fit-content;">Update Client</button>

            <!-- Upload Button -->
            <button class="btn btn-dark btn-sm mt-2 mr-3" style="width: fit-content;" onclick="openUploadPopup()">
                <i class="fa-solid fa-file-upload"></i> Upload Docs
            </button>

            <?php
            // Decode documents
            $documents = !empty($client['documents']) ? json_decode($client['documents'], true) : [];
            ?>

            <!-- Toggle Button -->
            <button class="btn btn-danger btn-sm mt-2 text-left text-decoration-none" type="button"
                id="toggleDocumentsButton" style="border: none; width:fit-content">
                Uploaded Documents
                <i class="fas fa-chevron-down" id="toggleIcon"></i>
            </button>

            <div class="mt-3" id="documents-list">

                <!-- If NO documents uploaded -->
                <?php if (empty($documents)): ?>
                    <p class="text-muted mt-2" id="documentsContent" style="display: none;">No Documents Uploaded</p>

                <?php else: ?>
                    <!-- If documents exist -->
                    <div id="documentsContent" style="display: none;">
                        <ul class="list-group list-group-flush">
                            <?php foreach ($documents as $doc):
                                $filePath = "uploads/client_docs/" . $doc;
                                $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
                            ?>
                                <li class="list-group-item d-flex justify-content-between align-items-center border-0">
                                    <?= $doc; ?>

                                    <?php if ($ext === 'pdf' || in_array($ext, ['doc', 'docx', 'txt'])): ?>
                                        <a href="<?= $filePath; ?>" target="_blank" class="btn btn-sm btn-secondary">View</a>
                                    <?php else: ?>
                                        <a href="<?= $filePath; ?>" target="_blank">
                                            <img src="<?= $filePath; ?>" alt="Document" style="max-height:50px;">
                                        </a>
                                    <?php endif; ?>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>

            </div>

        </div>
    </div>



    <!-- RIGHT SIDE: SERVICE DETAILS -->
    <div class="card shadow mb-4">
        <div class="card-header bg-info text-white">
            <h4>Service Details</h4>
        </div>
        <div class="card-body">
            <p><strong>Service:</strong> <?= $client['service']; ?></p>
            <p><strong>Service Date:</strong> <?= $client['service_date']; ?></p>
            <p><strong>Warranty:</strong> <?= $client['warranty']; ?></p>
            <p><strong>Service Covered:</strong> <?= $client['service_covered']; ?></p>
            <p><strong>Terms & Conditions:</strong> <?= $client['service_term_condition']; ?></p>
        </div>
    </div>

    <!-- *********************** PENDING WORK DETAILS ************************ -->
    <div class="card shadow mb-4">
        <div class="card-header bg-info text-white">
            <h4>Pending Work</h4>
        </div>
        <div class="card-body">
            <button onclick="window.location.href='add-pending-work.php?client_id=<?= $client_id; ?>'" class="btn btn-success btn-sm mb-3" style="width: fit-content;">Add Pending Work</button>

            <div class="table-responsive">
                <table class="table table-bordered text-center">
                    <thead class="">
                        <tr>
                            <th>Sr.No.</th>
                            <th>Work Description</th>
                            <th>Assigned To</th>
                            <th>Due Date</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        if (mysqli_num_rows($pending_works) > 0) {
                            $count = 1;
                            while ($row = mysqli_fetch_assoc($pending_works)) {
                        ?>
                                <tr>
                                    <td><?= $count++; ?></td>
                                    <td><?= $row['work_description']; ?></td>
                                    <td><?= $row['assigned_to']; ?></td>
                                    <td><?= $row['due_date']; ?></td>
                                    <td><?= $row['status']; ?></td>
                                    <td>
                                        <button onclick="window.location.href='update-pending-work.php?work_id=<?= $row['id']; ?>'" class="btn btn-sm btn-dark">Update</button>
                                    </td>
                                </tr>
                        <?php
                            }
                        } else {
                            echo "<tr><td colspan='6'>No Pending Work Found</td></tr>";
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>


    <!-- *********************** GST DETAILS (Only if applied) ************************ -->

    <?php if ($client['apply_gst'] == 1): ?>
        <div class="card shadow mb-4">
            <div class="card-header bg-info text-white">
                <h4>GST Details</h4>
            </div>
            <div class="card-body">
                <p><strong>GST Applied:</strong> Yes (18%)</p>
                <p><strong>GST Amount:</strong> <?= number_format($gst_amount, 2); ?></p>
                <p><strong>Billing Address:</strong> <?= $client['billing_address']; ?></p>
                <p><strong>Shipping Address:</strong> <?= $client['shipping_address']; ?></p>
                <p><strong>GST Invoice No:</strong> <?= $client['gst_invoice_no']; ?></p>
            </div>
        </div>
    <?php endif; ?>

    <!-- ************************ PAYMENT DETAILS ************************ -->

    <div class="card mb-4 shadow">
        <div class="card-header bg-info text-white">
            <h4>Payment Details</h4>
        </div>

        <div class="card-body">
            <div class="row mb-3">

                <div class="col-md-4">
                    <strong>Base Amount:</strong> <?= number_format($base_amount, 2); ?>
                </div>

                <?php if ($client['apply_gst'] == 1): ?>
                    <div class="col-md-4">
                        <strong>GST (18%):</strong> <?= number_format($gst_amount, 2); ?>
                    </div>
                <?php endif; ?>

                <div class="col-md-4">
                    <strong>Grand Total:</strong> <?= number_format($grand_total, 2); ?>
                </div>

                <div class="col-md-4 mt-3">
                    <strong>Total Paid:</strong> <?= number_format($total_paid, 2); ?>
                </div>

                <div class="col-md-4 mt-3">
                    <strong>Balance:</strong> <?= number_format($balance, 2); ?>
                </div>

            </div>

            <!-- PAYMENT HISTORY -->
            <div class="table-responsive">
                <table class="table table-bordered text-center">
                    <thead class="">
                        <tr>
                            <th>Sr. No.</th>
                            <th>Payment Date</th>
                            <th>Paid Amount</th>
                            <th>Payment Gateway</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $serial_no = 1;
                        if (mysqli_num_rows($payments) > 0) {
                            while ($row = mysqli_fetch_assoc($payments)) {
                        ?>
                                <tr>
                                    <td><?= $serial_no++; ?></td>
                                    <td><?= $row['payment_date']; ?></td>
                                    <td><?= $row['paid_amount']; ?></td>
                                    <td><?= $row['payment_gateway']; ?></td>
                                    <td>
                                        <button onclick="window.location.href='update-payment.php?id=<?= $client['id']; ?>&payment_id=<?= $row['id']; ?>'" class="btn btn-sm btn-dark">Update</button>
                                        <a href=""></a>
                                    </td>
                                </tr>
                        <?php
                            }
                        } else {
                            echo "<tr><td colspan='6'>No Payment Records Found</td></tr>";
                        }
                        ?>
                    </tbody>
                </table>
            </div>

        </div>
    </div>

</div>


<!-- UPLOAD DOCUMENT POPUP -->
<div id="uploadPopup" class="popup-overlay">
    <div class="popup-box">
        <h2>Upload Documents</h2>
        <p class="subtitle">Select document file and upload</p>

        <form id="uploadForm" action="upload-client-docs.php?id=<?= $client['id']; ?>" method="POST" enctype="multipart/form-data">

            <label class="input-label">Upload Document</label>
            <input type="file" name="documents[]" multiple class="file-input" required>

            <input type="hidden" name="client_id" value="<?= $client['id']; ?>">

            <button type="submit" class="upload-btn">Upload</button>
        </form>

        <button class="close-btn" onclick="closeUploadPopup()">Close</button>
    </div>
</div>

<script>
    function openUploadPopup() {
        document.getElementById("uploadPopup").style.display = "flex";
    }

    function closeUploadPopup() {
        document.getElementById("uploadPopup").style.display = "none";
    }

    // Get references to the elements
    const toggleButton = document.getElementById('toggleDocumentsButton');
    const documentsContent = document.getElementById('documentsContent');
    const toggleIcon = document.getElementById('toggleIcon');

    // Function to toggle visibility of documents
    toggleButton.addEventListener('click', function() {
        // Toggle the display of the document content
        if (documentsContent.style.display === 'none' || documentsContent.style.display === '') {
            documentsContent.style.display = 'block';
            documentsContent.style.transition = '0.35s ease-out';
            toggleIcon.classList.remove('fa-chevron-down');
            toggleIcon.classList.add('fa-chevron-up');
        } else {
            documentsContent.style.display = 'none';
            toggleIcon.classList.remove('fa-chevron-up');
            toggleIcon.classList.add('fa-chevron-down');
        }
    });
</script>

<?php
include('includes/scripts.php');
include('includes/footer.php');
?>
<?php ob_end_flush(); ?>