<?php
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);

ob_start();

include_once("include/head.php");

function sanitizeInput($input) {
    return htmlspecialchars(strip_tags(trim($input)));
}

if (!isset($_GET['id']) || empty($_GET['id'])) {
    die("Client ID is required");
}

$client_id = sanitizeInput($_GET['id']);

// Fetch client data
$sql = "SELECT id, assigned_to, name, email, phone FROM clients WHERE id = ?";
$stmt = mysqli_prepare($conn, $sql);
if ($stmt) {
    mysqli_stmt_bind_param($stmt, 'i', $client_id);
    mysqli_stmt_execute($stmt);

    // Bind result variables
    mysqli_stmt_bind_result($stmt, $id, $assigned_to, $name, $email, $phone);
    
    if (mysqli_stmt_fetch($stmt)) {
        $client = [
            'id' => $id,
            'assigned_to' => $assigned_to,
            'name' => $name,
            'email' => $email,
            'phone' => $phone,
        ];
    } else {
        die("Client not found");
    }

    mysqli_stmt_close($stmt);
} else {
    die("Error preparing client query: " . mysqli_error($conn));
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize input data
    $call_date = sanitizeInput($_POST['call_date']);
    $call_status = sanitizeInput($_POST['call_status']);
    $create_proposal = isset($_POST['create_proposal']) ? $_POST['create_proposal'] : 0;
    $interested_in = isset($_POST['interested_in']) ? $_POST['interested_in'] : [];
    $interested_in_string = implode(",", $interested_in);
    $budget = ($call_status == 'interested') ? sanitizeInput($_POST['budget']) : NULL;
    $quantity = ($call_status == 'interested') ? sanitizeInput($_POST['quantity']) : NULL;

    // Determine follow-up date based on call status
    $followup_date = NULL;
    if ($call_status == 'custom_container') {
        $custom_container = '1';
    } else {
        $custom_container = '0';
        $followup_date = sanitizeInput($_POST['followup_date_' . $call_status]);
    }

    // Check for duplicate follow-up
    $duplicate_check_sql = "SELECT COUNT(*) AS count FROM follow_ups WHERE client_id = ? AND call_status = ? AND call_date = ?";
    $stmt = mysqli_prepare($conn, $duplicate_check_sql);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, 'iss', $client_id, $call_status, $call_date);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_bind_result($stmt, $count);
        mysqli_stmt_fetch($stmt);
        mysqli_stmt_close($stmt);
    } else {
        die("Error preparing duplicate check statement: " . mysqli_error($conn));
    }

    if ($count > 0) {
        $_SESSION['error_message'] = "Duplicate follow-up entry found. Please modify the details.";
    } else {
        // Insert follow-up
        $sql = "INSERT INTO follow_ups (client_id, call_date, call_status, interested_in, budget, quantity, followup_date, 
            remarks_interested, remarks_not_interested, remarks_busy, remarks_follow_up, remarks_wrong_no, remarks_meeting, remarks_visit, created_by, updated_by, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = mysqli_prepare($conn, $sql);
        if ($stmt) {
            // Set your remark variables according to your form input
            $remarks_interested = $call_status == 'interested' ? sanitizeInput($_POST['remarks_interested_in']) : NULL;
            $remarks_not_interested = $call_status == 'not_interested' ? sanitizeInput($_POST['remarks_not_interested']) : NULL;
            $remarks_busy = $call_status == 'busy' ? sanitizeInput($_POST['remarks_busy']) : NULL;
            $remarks_follow_up = $call_status == 'follow_up' ? sanitizeInput($_POST['remarks_follow_up']) : NULL;
            $remarks_wrong_no = $call_status == 'wrong_no' ? sanitizeInput($_POST['remarks_wrong_no']) : NULL;
            $remarks_meeting = $call_status == 'meeting' ? sanitizeInput($_POST['remarks_meeting']) : NULL;
            $remarks_visit = $call_status == 'visit' ? sanitizeInput($_POST['remarks_visit']) : NULL;

            mysqli_stmt_bind_param($stmt, 'isssssssssssssiiss',
                $client_id, 
                $call_date, 
                $call_status, 
                $interested_in_string, 
                $budget, 
                $quantity, 
                $followup_date, 
                $remarks_interested, 
                $remarks_not_interested, 
                $remarks_busy, 
                $remarks_follow_up, 
                $remarks_wrong_no, 
                $remarks_meeting, 
                $remarks_visit, 
                $logginedUserid,
                $logginedUserid,
                $currentDateTime,
                $currentDateTime
            );

            if (mysqli_stmt_execute($stmt)) {
               if ($create_proposal == '1') {
                   
                    if ($create_proposal != '1') {
                        die("Create proposal value is not set to '1'. Current value: " . $create_proposal);
                    }
    
                    $sql = "INSERT INTO proposals (client_id, status, interested_in, quantity, price, remarks, created_by, updated_by, created_at, updated_at)
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    $stmt = mysqli_prepare($conn, $sql);
                    
                    if (!$stmt) {
                        die("Error preparing proposal statement: " . mysqli_error($conn));
                    }
                
                    mysqli_stmt_bind_param($stmt, 'isssssiiss',
                        $client_id, 
                        $call_status, 
                        $interested_in_string, 
                        $quantity, 
                        $budget, 
                        $remarks_interested, 
                        $logginedUserid,
                        $logginedUserid,
                        $currentDateTime,
                        $currentDateTime
                    );
                
                    if (!mysqli_stmt_execute($stmt)) {
                        die("Error executing proposal insert: " . mysqli_stmt_error($stmt));
                    }
                
                    mysqli_stmt_close($stmt);
                }

                if ($custom_container == '1') {
                    $sql = "INSERT INTO custom_orders (client_id) VALUES (?)";
                    $stmt = mysqli_prepare($conn, $sql);
                    if ($stmt) {
                        mysqli_stmt_bind_param($stmt, 'i', $client_id);
                        mysqli_stmt_execute($stmt);
                        $order_id = mysqli_stmt_insert_id($stmt);
                        mysqli_stmt_close($stmt);

                        $stmt = mysqli_prepare($conn, "INSERT INTO custom_order_items (order_id) VALUES (?)");
                        if ($stmt) {
                            mysqli_stmt_bind_param($stmt, 'i', $order_id);
                            mysqli_stmt_execute($stmt);
                            mysqli_stmt_close($stmt);
                        }
                    }
                }

                $_SESSION['success_message'] = "Follow-up details saved successfully!";
            } else {
                $_SESSION['error_message'] = "Error executing follow-up query: " . mysqli_stmt_error($stmt);
            }
        } else {
            die("Error preparing follow-up insert statement: " . mysqli_error($conn));
        }
    }

    mysqli_close($conn);
    
    if ($custom_container == '1') {
         header("Location: custom_container.php");
    }
    header("Location: calls.php");
    exit();
}

ob_end_flush();
?>


<style>
@media (min-width: 992px) {
    .modal-lg, .modal-xl {
        max-width: 75% !important;
    }
}
.modal-body{
    
    overflow:hidden !important;
}
</style>
<div class="main-panel">
    <div class="content-wrapper">
       
        <div class="card">
            <div class="card-body">
                <div class="row align-items-center justify-content-between">
                    <h4 class="card-title mb-0">EDIT CLIENT FOLLOW UP</h4>
                    <div class="d-flex">
                        <a href="client-follow-up-history.php?id=<?php echo $client_id?>"  data-toggle="modal" data-target="#callHistoryModal" class="btn btn-primary btn-sm">View History</a>
                        <!--<a href="" class="btn btn-danger btn-sm ml-2">Go Back</a>-->
                    </div>
                </div>

                <div class="row mt-3">
                    <div class="col-12">
                      <form class="cmxform" id="commentForm" method="post" action="" enctype="multipart/form-data" onsubmit="return validateForm()">
                        <fieldset>
                            <div class="row">
                                <div class="form-group col-md-6">
                                    <label for="client_name">Client Name</label>
                                    <input class="form-control" type="text" name="client_name" value="<?php echo htmlspecialchars($client['name']); ?>" readonly>
                                </div>
                                <div class="form-group col-md-6">
                                    <label for="phone">Phone</label>
                                    <input class="form-control" type="text" name="phone" value="<?php echo htmlspecialchars($client['phone']); ?>" readonly >
                                </div>
                                
                                <div class="form-group col-md-6">
                                    <label for="call_date">Call Date</label>
                                    <input class="form-control" type="text" id="call_date" name="call_date" value="<?php echo date('d-m-Y'); ?>" readonly>
                                </div>
                    
                                <div class="form-group col-md-6">
                                    <label for="call_status">Call Status</label>
                                    <select id="call_status" class="form-control" name="call_status">
                                        <option value="">Choose status</option>
                                        <option value="interested">Interested</option>
                                        <option value="not_interested">Not Interested</option>
                                        <option value="busy">Busy</option>
                                        <option value="follow_up">Follow Up</option>
                                        <option value="wrong_no">Wrong Number</option>
                                        <option value="meeting">Meeting</option>
                                        <option value="visit">Visit</option>
                                        <option value="custom_container">Custom Container</option>
                                    </select>
                                </div>
                            </div>
                    
                                    
                            <div id="interested_fields" class="conditional-field row" style="display: none;">
                                <div class="form-group col-md-12">
                                    <label for="product_type">Product Type</label>
                                    <?php
                                    $typesQuery = "SELECT type_id, type_name FROM product_type";
                                    $typesResult = $conn->query($typesQuery);
                            
                                    if ($typesResult && $typesResult->num_rows > 0) {
                                        echo '<div id="product_types" class="row p-3">';
                                        while ($row1 = $typesResult->fetch_assoc()) {
                                            $id = $row1['type_id'];
                                            $name = $row1['type_name']; 
                                            ?>
                                            <div class="form-group col-md-3 mb-0">
                                                <input type="checkbox" id="product_type<?php echo $id; ?>" name="product_type[]" value="<?php echo $id; ?>" onchange="fetchProducts()"> 
                                                <label for="product_type<?php echo $id; ?>"> <?php echo $name; ?></label>
                                            </div>
                                            <?php
                                        }
                                        echo '</div>';
                                    } else {
                                        echo '<p>No product types found.</p>';
                                    }
                                    ?>
                                </div>
                                <div class="form-group col-md-12">
                                    <label for="interested_in">Interested In</label>
                                    <div id="products_container" class="row p-3"></div>
                                </div>
                                
                                <div class="form-group col-md-6">
                                    <label for="budget">Budget</label>
                                    <input class="form-control" type="text" id="budget" name="budget">
                                </div>
                                <div class="form-group col-md-6">
                                    <label for="followup_date">Follow Up Date</label>
                                    <input class="form-control" type="datetime-local" id="followup_date" name="followup_date">
                                </div>
                                <div class="form-group col-md-6">
                                    <label for="quantity">Quantity</label>
                                    <input class="form-control" type="number" id="quantity" name="quantity">
                                </div>
                                <div class="form-group col-md-6">
                                    <label for="remarks_interested_in">Remarks</label>
                                    <textarea class="form-control" id="remarks_interested_in" name="remarks_interested_in"></textarea>
                                </div>
                                
                                <div class="form-group col-md-3">
                                    <!--<input type="radio" id="create_proposal" name="create_proposal" value="1">-->
                                    <input type="checkbox" id="create_proposal" name="create_proposal" value="1"> 
                                    <label for="create_proposal"> Create Proposal</label> 
                                </div>
                                
                            </div>
                    
                            <div id="not_interested_fields" class="conditional-field row" style="display: none;">
                                <div class="form-group col-md-6">
                                    <label for="remarks_not_interested">Remarks</label>
                                    <textarea class="form-control" id="remarks_not_interested" name="remarks_not_interested"></textarea>
                                </div>
                            </div>
                    
                            <div id="busy_fields" class="conditional-field row" style="display: none;">
                                <div class="form-group col-md-6">
                                    <label for="followup_date_busy">Follow Up Date</label>
                                    <input class="form-control" type="datetime-local" id="followup_date_busy" name="followup_date_busy">
                                </div>
                                <div class="form-group col-md-6">
                                    <label for="remarks_busy">Remarks</label>
                                    <textarea class="form-control" id="remarks_busy" name="remarks_busy"></textarea>
                                </div>
                            </div>
                    
                            <div id="follow_up_fields" class="conditional-field row" style="display: none;">
                                <div class="form-group col-md-6">
                                    <label for="followup_date_follow_up">Follow Up Date</label>
                                    <input class="form-control" type="datetime-local" id="followup_date_follow_up" name="followup_date_follow_up">
                                </div>
                                <div class="form-group col-md-6">
                                    <label for="remarks_follow_up">Remarks</label>
                                    <textarea class="form-control" id="remarks_follow_up" name="remarks_follow_up"></textarea>
                                </div>
                            </div>
                    
                            <div id="wrong_no_fields" class="conditional-field row" style="display: none;">
                                <div class="form-group col-md-6">
                                    <label for="remarks_wrong_no">Remarks</label>
                                    <textarea class="form-control" id="remarks_wrong_no" name="remarks_wrong_no"></textarea>
                                </div>
                            </div>
                            
                            <div id="meeting_fields" class="conditional-field row" style="display: none;">
                                <div class="form-group col-md-6">
                                    <label for="remarks_meeting">Remarks</label>
                                    <textarea class="form-control" id="remarks_meeting" name="remarks_meeting"></textarea>
                                </div>
                                <div class="form-group col-md-6">
                                    <label for="followup_date_meeting">Follow Up Date</label>
                                    <input class="form-control" type="datetime-local" id="followup_date_meeting" name="followup_date_meeting">
                                </div>
                            </div>
                    
                            <div id="visit_fields" class="conditional-field row" style="display: none;">
                                <div class="form-group col-md-6">
                                    <label for="remarks_visit">Remarks</label>
                                    <textarea class="form-control" id="remarks_visit" name="remarks_visit"></textarea>
                                </div>
                                <div class="form-group col-md-6">
                                    <label for="followup_date_visit">Follow Up Date</label>
                                    <input class="form-control" type="datetime-local" id="followup_date_visit" name="followup_date_visit">
                                </div>
                            </div>
                    
                            <input class="btn btn-primary" type="submit" value="Submit" name="submit">
                        </fieldset>
                    </form>

                        
                        </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="callHistoryModal" tabindex="-1" role="dialog" aria-labelledby="callHistoryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="callHistoryModalLabel">Call History</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            
            <?php
                $sql = "SELECT clients.id, clients.name, clients.phone, follow_ups.call_date, follow_ups.call_status
                        FROM clients
                        LEFT JOIN follow_ups ON clients.id = follow_ups.client_id
                        WHERE clients.id = $client_id";
                
                $result = mysqli_query($conn, $sql);
                
                if (!$result) {
                    die("Error executing query: " . mysqli_error($conn));
                }
                
                $client = mysqli_fetch_assoc($result);
                
                if (!$client) {
                    die("Client not found");
                }
                
                $history_sql = "SELECT follow_ups.*, 
                                       GROUP_CONCAT(products.name SEPARATOR ', ') AS interested_products
                                FROM follow_ups
                                LEFT JOIN products ON FIND_IN_SET(products.id, follow_ups.interested_in)
                                WHERE follow_ups.client_id = $client_id 
                                GROUP BY follow_ups.id 
                                ORDER BY follow_ups.call_date DESC";
                
                $follow_up_result = mysqli_query($conn, $history_sql);
                
                if (!$follow_up_result) {
                    die("Error executing query: " . mysqli_error($conn));
                }
                
                $follow_ups = [];
                while ($row = mysqli_fetch_assoc($follow_up_result)) {
                    $follow_ups[] = $row;
                }
                
                mysqli_free_result($result);
                mysqli_free_result($follow_up_result);
            ?>
            <div class="modal-body" style="overflow:hidden">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Call Date</th>
                            <th>Call Status</th>
                            <th>Interested In</th>
                            <th>Budget</th>
                            <th>Quantity</th>
                            <th>Follow Up Date</th>
                            <th>Remarks</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($follow_ups)): ?>
                            <tr>
                                <td colspan="7">No follow-up history available.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($follow_ups as $follow_up): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($follow_up['call_date'] ?? 'NA'); ?></td>
                                    <td><?php echo htmlspecialchars($follow_up['call_status'] ?? 'NA'); ?></td>
                                    <td><?php echo htmlspecialchars($follow_up['interested_products'] ?? '') ?: 'NA'; ?></td>
                                    <td><?php echo htmlspecialchars($follow_up['budget'] ?? 'NA'); ?></td>
                                    <td><?php echo htmlspecialchars($follow_up['quantity'] ?? 'NA'); ?></td>
                                    <td><?php echo htmlspecialchars($follow_up['followup_date'] ?? 'NA'); ?></td>
                                    <td>
                                        <?php
                                        $remarks = '';
                                        switch ($follow_up['call_status']) {
                                            case 'interested':
                                                $remarks = $follow_up['remarks_interested'] ?? 'NA';
                                                break;
                                            case 'not_interested':
                                                $remarks = $follow_up['remarks_not_interested'] ?? 'NA';
                                                break;
                                            case 'busy':
                                                $remarks = $follow_up['remarks_busy'] ?? 'NA';
                                                break;
                                            case 'follow_up':
                                                $remarks = $follow_up['remarks_follow_up'] ?? 'NA';
                                                break;
                                            case 'wrong_no':
                                                $remarks = $follow_up['remarks_wrong_no'] ?? 'NA';
                                                break;
                                             case 'meeting':
                                                $remarks = $follow_up['remarks_meeting'] ?? 'NA';
                                            case 'visit':
                                                $remarks = $follow_up['remarks_visit'] ?? 'NA';
                                                break;
                                                default:
                                                $remarks = 'NA';
                                        }
                                        echo htmlspecialchars($remarks);
                                        ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    function clearFields(fieldIds) {
        fieldIds.forEach(function(id) {
            var field = document.getElementById(id);
            if (field) {
                if (id.startsWith('product_type') || ('create_proposal')) {
                    return;
                }
                field.value = '';
                field.classList.remove('is-invalid');
                var errorElement = document.getElementById(id + '_error');
                if (errorElement) {
                    errorElement.style.display = 'none';
                }
            }
        });
    }
    
    function updateFormFields() {
        var status = document.getElementById('call_status').value;

        document.querySelectorAll('.conditional-field').forEach(function(field) {
            field.style.display = 'none';
            clearFields(Array.from(field.querySelectorAll('input, select, textarea')).map(el => el.id));
        });

        if (status === 'interested') {
            document.getElementById('interested_fields').style.display = 'flex';
        } else if (status === 'not_interested') {
            document.getElementById('not_interested_fields').style.display = 'flex';
        } else if (status === 'busy') {
            document.getElementById('busy_fields').style.display = 'flex';
        } else if (status === 'follow_up') {
            document.getElementById('follow_up_fields').style.display = 'flex';
        } else if (status === 'wrong_no') {
            document.getElementById('wrong_no_fields').style.display = 'flex';
        } else if (status === 'meeting') {
            document.getElementById('meeting_fields').style.display = 'flex';
        } else if (status === 'visit') {
            document.getElementById('visit_fields').style.display = 'flex';
        }
    }

    updateFormFields();

    document.getElementById('call_status').addEventListener('change', function() {
        updateFormFields();
        fetchProducts();  // Fetch products whenever status changes
    });
    
    document.getElementById('commentForm').addEventListener('submit', function(event) {
        if (!validateForm()) {
            event.preventDefault();
            console.log('Form validation failed');
        } else {
            console.log('Form is valid and ready to submit');
        }
    });
});

function validateForm() {
    var status = document.getElementById('call_status').value;
    var valid = true;
    valid = checkRequiredFields(['call_date']);
    valid = checkRequiredFields(['call_status']);

    if (status === 'interested') {
        valid = checkRequiredFields(['interested_in', 'budget', 'followup_date', 'quantity', 'remarks_interested_in']);
    } else if (status === 'not_interested') {
        valid = checkRequiredFields(['remarks_not_interested']);
    } else if (status === 'busy') {
        valid = checkRequiredFields(['followup_date_busy', 'remarks_busy']);
    } else if (status === 'follow_up') {
        valid = checkRequiredFields(['followup_date_follow_up', 'remarks_follow_up']);
    } else if (status === 'wrong_no') {
        valid = checkRequiredFields(['remarks_wrong_no']);
    }else if (status === 'meeting') {
        valid = checkRequiredFields(['remarks_meeting']);
    }else if (status === 'visit') {
        valid = checkRequiredFields(['remarks_visit']);
    }

    return valid;
}

function checkRequiredFields(fieldIds) {
    var valid = true;
    fieldIds.forEach(function(id) {
        var field = document.getElementById(id);
        var errorElement = document.getElementById(id + '_error');

        if (!field.value.trim()) {
            valid = false;
            field.classList.add('is-invalid');
            if (!errorElement) {
                errorElement = document.createElement('div');
                errorElement.id = id + '_error';
                errorElement.classList.add('invalid-feedback');
                errorElement.innerText = 'This field is required.';
                field.parentNode.appendChild(errorElement);
            }
            errorElement.style.display = 'block';
        } else {
            field.classList.remove('is-invalid');
            if (errorElement) {
                errorElement.style.display = 'none';
            }
        }
    });
    return valid;
}

function fetchProducts() {
    var selectedTypes = [];
    document.querySelectorAll('input[name="product_type[]"]:checked').forEach(function(checkbox) {
        selectedTypes.push(checkbox.value);
    });

    console.log('Selected Types:', selectedTypes); 

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'fetch_products.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            document.getElementById('products_container').innerHTML = xhr.responseText;
        }
    };
    xhr.send('types=' + encodeURIComponent(JSON.stringify(selectedTypes)));
}

</script>


<?php include_once("include/footer.php"); ?>

</body>
</html>