<?php

// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);

session_start();
require_once "config.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']);

$sql = "SELECT * FROM clients WHERE id = $client_id";
$result = mysqli_query($conn, $sql);

if (!$result) {
    die("Error fetching client data: " . mysqli_error($conn));
}

$client = mysqli_fetch_assoc($result);

$assigned_to = $client['assigned_to'];

if (!$client) {
    die("Client not found");
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $call_date = sanitizeInput($_POST['call_date']);
    $call_status = sanitizeInput($_POST['call_status']);

    $interested_in = $call_status == 'connected' ? sanitizeInput($_POST['interested_in']) : NULL;
    $budget = $call_status == 'connected' ? sanitizeInput($_POST['budget']) : NULL;
    $followup_date = NULL;
    $quantity = $call_status == 'connected' ? sanitizeInput($_POST['quantity']) : NULL;

    if ($call_status == 'connected') {
        $remarks_connected = sanitizeInput($_POST['remarks_connected']);
        $followup_date = sanitizeInput($_POST['followup_date']);
    } elseif ($call_status == 'not_connected') {
        $remarks_not_connected = sanitizeInput($_POST['remarks_not_connected']);
    } elseif ($call_status == 'busy') {
        $followup_date = sanitizeInput($_POST['followup_date_busy']);
        $remarks_busy = sanitizeInput($_POST['remarks_busy']);
    } elseif ($call_status == 'follow_up') {
        $followup_date = sanitizeInput($_POST['followup_date_follow_up']);
        $remarks_follow_up = sanitizeInput($_POST['remarks_follow_up']);
    }
    
    $duplicate_check_sql = "SELECT * FROM follow_ups WHERE client_id = '$client_id' AND call_date = '$call_date'";
    $result_dup = mysqli_query($conn, $duplicate_check_sql);

    if (mysqli_num_rows($result_dup) > 0) {
        $_SESSION['error_message'] = "Duplicate follow-up entry found for the same date. Please modify the details.";
    } else {

        $sql = "INSERT INTO follow_ups (client_id, call_date, call_status, interested_in, budget, quantity, followup_date, 
                                        remarks_connected, remarks_not_connected, remarks_busy, remarks_follow_up)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
        $stmt = mysqli_prepare($conn, $sql);
        mysqli_stmt_bind_param($stmt, 'issssssssss', $client_id, $call_date, $call_status, $interested_in, $budget, $quantity,
                                            $followup_date, $remarks_connected, $remarks_not_connected, $remarks_busy, $remarks_follow_up);
    
        if (mysqli_stmt_execute($stmt)) {
           $_SESSION['success_message'] = "Follow-up details saved successfully!";
        } else {
            echo "Error: " . mysqli_error($conn);
        }
    
        mysqli_stmt_close($stmt);
    }
}
    
?>
<?php include_once("include/head.php"); ?>

<div class="main-panel">
    <div class="content-wrapper">
       <?php
        if (isset($_SESSION['success_message'])) {
            echo '<div class="alert alert-success">' . $_SESSION['success_message'] . '</div>';
            unset($_SESSION['success_message']); // Clear the message after displaying it
        }

        if (isset($_SESSION['error_message'])) {
            echo '<div class="alert alert-danger">' . $_SESSION['error_message'] . '</div>';
            unset($_SESSION['error_message']); // Clear the message after displaying it
        }
        ?>
        <div class="card">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3">
                        <h4 class="card-title">EDIT CLIENT FOLLOW UP</h4>
                    </div>
                </div>

                <div class="row">
                    <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="date" id="call_date" name="call_date">
                                    </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="connected">Connected</option>
                                            <option value="not_connected">Not Connected</option>
                                            <option value="busy">Busy</option>
                                            <option value="follow_up">Follow Up</option>
                                        </select>
                                    </div>
                                </div>

                                <!-- Conditional fields -->
                                <div id="connected_fields" class="conditional-field row" style="display: none;">
                                    <div class="form-group col-md-6">
                                        <label for="interested_in">Interested In</label>
                                        <select id="interested_in" class="form-control" name="interested_in">
                                            <option value="">Choose product</option>
                                            <?php
                                            $pro_sql = "SELECT name, id, sku FROM products WHERE status = '1'";
                                            $pro_result = mysqli_query($conn, $pro_sql);
                                            while ($product = mysqli_fetch_assoc($pro_result)) {
                                                echo "<option value=\"" . $product['id'] . "\">" . $product['name'] . " ( SKU " . $product['sku'] . " ) </option>";
                                            }
                                            ?>
                                        </select>
                                    </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="date" 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_connected">Remarks</label>
                                        <textarea class="form-control" id="remarks_connected" name="remarks_connected"></textarea>
                                    </div>
                                </div>

                                <div id="not_connected_fields" class="conditional-field row" style="display: none;">
                                    <div class="form-group col-md-6">
                                        <label for="remarks_not_connected">Remarks</label>
                                        <textarea class="form-control" id="remarks_not_connected" name="remarks_not_connected"></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="date" 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="date" 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>

                                <input class="btn btn-primary" type="submit" value="Submit" name="submit">
                            </fieldset>
                        </form>               
                        
                        </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    
     function clearFields(fieldIds) {
        fieldIds.forEach(function(id) {
            var field = document.getElementById(id);
            if (field) {
                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 === 'connected') {
            document.getElementById('connected_fields').style.display = 'flex';
        } else if (status === 'not_connected') {
            document.getElementById('not_connected_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';
        }
    }

    updateFormFields();

    document.getElementById('call_status').addEventListener('change', updateFormFields);
    
    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 === 'connected') {
        valid = checkRequiredFields(['interested_in', 'budget', 'followup_date', 'quantity', 'remarks_connected']);
    } else if (status === 'not_connected') {
        valid = checkRequiredFields(['remarks_not_connected']);
    } 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']);
    }

    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;
}
</script>


<?php include_once("include/footer.php"); ?>

</body>
</html>