<?php
include('dashboard.php');
require_once('dbconnection.php');

require 'vendor/autoload.php';
use Twilio\Rest\Client;

$account_sid = 'AC8bac449b32a1fe6070f736d142cbac1f';
$auth_token = '8e489af7dfa15b610298953e184de89d';

$client = new Client($account_sid, $auth_token);

$number = '+13322308524';

$fromCalls = $client->calls->read(['from' => $number]);
$toCalls   = $client->calls->read(['to'   => $number]);

$mergedCalls = [];
$uniqueSids = [];

foreach (array_merge($fromCalls, $toCalls) as $call) {
    if (!in_array($call->sid, $uniqueSids)) {
        $uniqueSids[] = $call->sid;
        $mergedCalls[] = $call;
    }
}

$myNumber = '+13322308524'; // Your own number

foreach ($mergedCalls as $call) {
    $direction = $call->direction;
    $from = $call->from;
    $to = $call->to;
    $status = $call->status;
    $date_time = $call->startTime ? $call->startTime->format('Y-m-d H:i:s') : '0000-00-00 00:00:00';
    $name = '';

    if ($from == $myNumber) {
        continue;
    }
    $checkQuery = "SELECT id FROM Contact WHERE from_number = '$from'";
    $checkResult = mysqli_query($con, $checkQuery);

    if (mysqli_num_rows($checkResult) > 0) {
        //error_log("Skipped (already exists): $from");
        continue;
    }

    $insertQuery = "INSERT INTO Contact (name, from_number, to_number, direction, call_status, date_time)
                    VALUES ('$name', '$from', '$to', '$direction', '$status', '$date_time')";

    if (mysqli_query($con, $insertQuery)) {
         //error_log("Inserted:: $from");
    } else {
        error_log("Insert error for $from: " . mysqli_error($con) . "<br>");

    }
}

    $i = 1;
    $sql = "SELECT * FROM Contact";
    $result = mysqli_query($con, $sql);
    if (mysqli_num_rows($result) > 0) {
?>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

<style>
.edit-icon {
    display: none;   /* default hidden */
    float: right;
    font-size: 14px;
    color: gray;
    cursor: pointer;
}


td.editable:hover .edit-icon {
    display: inline;
}

.dataTables_wrapper {
    padding: 25px;
}

/*main {*/
/*    height: 80vh;*/

/*}*/
body{
    background:#F6F6F3;
}
main {
    top: 89px !important;
    right: 1% !important;
    left: inherit!important;
    position: absolute;
    overflow: auto;
    height: 89%!important;
    width: 78%!important;
    background: #eaedf1;
    border-radius: 8px;
}
#addContactFormContainer{
    max-width: calc(100% - 32px)!important;
}
main h1 {
    position: absolute;
    top: -9px;
    left: 45%;
    font-size: 29px;
    text-decoration: underline;
    font-weight: 600;
    color: #2d54c6;
}
@media (min-width:768px) and (max-width:1024px){
    #addContactFormContainer form{
        flex-direction: column;
    }   
 
    main {
        height: 88% !important;
    width: 77% !important;
    }

}
@media (max-width: 918px) {
    main {
width:76% !important;
    }
}
@media (max-width:767px) {
    main h1 {
        position: absolute;
         top: 0;
        left: 40%;
        font-size: 24px;
        width: 100%;
    }
    
        main {
        width: 96% !important;
        right: 2% !important;
        height: 85% !important;
           transform: inherit !important;  
    }
        #addContactFormContainer form{
        flex-direction: column;
    }   
    #addContactFormContainer{      
        width: calc(95% - 16px);
    }

    .dataTables_wrapper {
        min-width: 830px;
    }

    .dataTables_wrapper .dataTables_length {
        float: left;
        margin-top: 10px;
        margin-left: 10px;
    }

    .dataTables_wrapper .dataTables_filter {
        float: right;
        margin-left: 20px !important;
    }
}   
    #addContactFormContainer {
        display: flex;
        justify-content: center;
        margin: 40px auto 20px auto;
        padding: 20px;
        background-color: #f8f9fa;
        border-radius: 8px;
        box-shadow: 0 0 10px rgba(0,0,0,0.05);
        max-width: 900px;
        flex-wrap: wrap;
        gap: 10px;
        margin-top: 60px;

    }

    #addContactForm input,
    #addContactForm button {
        padding: 10px;
        border: 1px solid #ccc;
        border-radius: 6px;
        font-size: 14px;
    }

    #addContactForm input {
        flex: 1;
        min-width: 220px;
    }

    #addContactForm button {
        background-color: #0263e0;
        color: white;
        border: none;
        cursor: pointer;
        transition: background-color 0.3s ease;
    }

    #addContactForm button:hover {
        background-color: #030b5d;
    }

    @media (max-width: 576px) {
        #addContactFormContainer {
            padding: 15px;
        }

        #addContactForm input, 
        #addContactForm button {
            width: 100%;
            flex: unset;
        }
    }
</style>

<main>
    <h1>Contacts</h1>
    <div class="main-content-inner">
        <div class="row">
            <div class="col-ml-12"></div>
        </div>
          <div id="addContactFormContainer">
            <form id="addContactForm" method="POST" action="" style="display: flex; flex-wrap: wrap; gap: 10px; width: 100%;">
                <input type="text" name="name" placeholder="Enter contact name" required>
                <input type="text" name="from_number" placeholder="Enter contact number" required>
                <button type="submit">Add Contact</button>
            </form>
         </div>

        <table id="example" class="display" style="width:100%">
            <thead>
                <tr>
                    <th>Sr.No</th>
                    <th>Name</th>
                    <th>Contacts</th>
                    <!--<th>To</th>-->
                    <!--<th>Direction</th>-->
                    <!--<th>Status</th>-->
                    <th>Date and Time</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $i = 1;
                while ($row = mysqli_fetch_assoc($result)) {
                ?>
                    <tr>
                        <td><?php echo $i++; ?></td>
                            <td class="editable" data-id="<?php echo $row['id']; ?>" data-column="name">
                                <?php echo htmlspecialchars($row['name']); ?>
                                <span class="edit-icon">✏️</span>
                            </td>
                            
                            <td class="editable" data-id="<?php echo $row['id']; ?>" data-column="from_number">
                                <?php echo htmlspecialchars($row['from_number']); ?>
                                <span class="edit-icon">✏️</span>
                            </td>
                            <!--<td class="editable" data-id="<?php //echo $row['id']; ?>" data-column="to_number">-->
                        <!--    <?php //echo htmlspecialchars($row['to_number']); ?> <span class="edit-icon">✏️</span>-->
                        <!--</td>-->
                        <!--<td><?php //echo $row['direction']; ?></td>-->
                        <!--<td><?php //echo $row['call_status']; ?></td>-->
                        <td><?php echo $row['date_time']; ?></td>
                        <td>
                            <form method="POST" action="" onsubmit="return confirm('Are you sure you want to delete this contact?');" style="display:inline;">
                                <input type="hidden" name="delete_id" value="<?php echo $row['id']; ?>">
                                <button type="submit" name="delete_contact" style="background: #e3342f; color: white; border: none; padding: 5px 10px; border-radius: 5px;">Delete</button>
                            </form>
                        </td>

                    </tr>
                <?php } ?>
            </tbody>
            <tfoot>
                <tr>
                    <th>Sr.No</th>
                    <th>Name</th>
                    <th>Contacts</th>
                    <!--<th>To</th>-->
                    <!--<th>Direction</th>-->
                    <!--<th>Status</th>-->
                    <th>Date and Time</th>
                </tr>
            </tfoot>
        </table>
    </div>
</main>

<script>
$(document).ready(function () {
    $('#example').DataTable();

    // Click on ✏️ icon triggers inline edit
    $('#example tbody').on('click', '.editable .edit-icon', function (e) {
        e.stopPropagation(); // avoid bubbling to td
        const td = $(this).closest('.editable');

        // Avoid multiple input fields
        if (td.find('input').length > 0) return;

        const originalText = td.contents().filter(function () {
            return this.nodeType === 3;
        }).text().trim();

        const id = td.data('id');
        const column = td.data('column');

        const input = $('<input type="text" class="form-control form-control-sm">').val(originalText);
        td.html(input);
        input.focus();

        // Handle update on blur
        input.on('blur', function () {
            const newValue = $(this).val();
            td.html(newValue + ' <span class="edit-icon">✏️</span>');

            // Send AJAX update to server
            $.ajax({
                url: 'update_cell.php',
                method: 'POST',
                data: {
                    id: id,
                    column: column,
                    value: newValue
                },
                success: function (response) {
                    console.log(response);
                    console.log('Update success:', response);
                },
                error: function () {
                    alert('Update failed');
                }
            });
        });
    });
});
</script>
<?php
include('footer.php');
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $from_number = trim($_POST['from_number']);
    $date_time = date('Y-m-d H:i:s');
    
    // Option 1: using strtr (manual mapping)
    $name = strtr($name, [
        'á' => 'a', 'à' => 'a', 'ä' => 'a', 'â' => 'a',
        'Á' => 'A', 'À' => 'A', 'Â' => 'A', 'Ä' => 'A',
        'é' => 'e', 'è' => 'e', 'ë' => 'e', 'ê' => 'e',
        'É' => 'E', 'È' => 'E', 'Ê' => 'E', 'Ë' => 'E',
        'í' => 'i', 'ì' => 'i', 'ï' => 'i', 'î' => 'i',
        'Í' => 'I', 'Ì' => 'I', 'Ï' => 'I', 'Î' => 'I',
        'ó' => 'o', 'ò' => 'o', 'ö' => 'o', 'ô' => 'o',
        'Ó' => 'O', 'Ò' => 'O', 'Ö' => 'O', 'Ô' => 'O',
        'ú' => 'u', 'ù' => 'u', 'ü' => 'u', 'û' => 'u',
        'Ú' => 'U', 'Ù' => 'U', 'Û' => 'U', 'Ü' => 'U',
        'ñ' => 'n', 'Ñ' => 'N',
        'ç' => 'c', 'Ç' => 'C'
    ]);

    if (!empty($name) && !empty($from_number)) {
        $stmt = $con->prepare("INSERT INTO Contact (name, from_number, date_time) VALUES (?, ?, ?)");
        $stmt->bind_param("sss", $name, $from_number, $date_time);

        if ($stmt->execute()) {
            echo "<script>
                setTimeout(function() {
                    window.location.href = '" . $_SERVER['PHP_SELF'] . "';
                }, 2000);
            </script>";
            exit();
        } else {
            echo "❌ Failed to add contact: " . $con->error;
        }
    } else {
        echo "❌ Name and Contact Number are required.";
    }
}



if (isset($_POST['delete_contact']) && isset($_POST['delete_id'])) {
    $delete_id = intval($_POST['delete_id']);

    $stmt = $con->prepare("DELETE FROM Contact WHERE id = ?");
    $stmt->bind_param("i", $delete_id);

    if ($stmt->execute()) {
        echo "<script>
            alert('Contact deleted successfully.');
            window.location.href = '" . $_SERVER['PHP_SELF'] . "';
        </script>";
        exit();
    } else {
        echo "❌ Failed to delete contact: " . $con->error;
    }
}


?>