
<?php

$range = isset($_GET['range']) ? sanitize_text_field($_GET['range']) : '30';

$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$end_date   = isset($_GET['end_date']) ? $_GET['end_date'] : '';

if($range == "7"){
    $start = date('Y-m-d H:i:s', strtotime('-7 days'));
}
elseif($range == "30"){
    $start = date('Y-m-d H:i:s', strtotime('-30 days'));
}
elseif($range == "90"){
    $start = date('Y-m-d H:i:s', strtotime('-90 days'));
}
elseif($range == "custom" && $start_date && $end_date){
    $start = $start_date . " 00:00:00";
    $end   = $end_date . " 23:59:59";
}
else{
    $start = date('Y-m-d H:i:s', strtotime('-30 days'));
}

if(empty($end)){
    $end = current_time('mysql');
}

?>

<?php
global $wpdb;

$submissions_table  = $wpdb->prefix . 'vform_userinput';
$views_table        = $wpdb->prefix . 'vform_fields';

$last_30_days = date('Y-m-d H:i:s', strtotime('-30 days'));


/* -----------------------------
   TOTAL VIEWS (unique IP)
--------------------------------*/
$total_views = $wpdb->get_var("
    SELECT COUNT(DISTINCT ip)
    FROM $views_table
    WHERE type='view'
    AND created_at BETWEEN '$start' AND '$end'
");


/* -----------------------------
   TOTAL SUBMISSIONS
--------------------------------*/
$total_submissions = $wpdb->get_var("
    SELECT COUNT(*)
    FROM $submissions_table
    WHERE STR_TO_DATE(currentdate,'%M %e, %Y, %h:%i %p')
    BETWEEN '$start' AND '$end'
");


/* -----------------------------
   STARTS
--------------------------------*/
$total_starts = $wpdb->get_var("
    SELECT COUNT(DISTINCT ip)
    FROM $views_table
    WHERE type='start'
    AND created_at BETWEEN '$start' AND '$end'
");


/* -----------------------------
   COMPLETION RATE
--------------------------------*/
$completion_rate = $total_starts ? round(($total_submissions / $total_starts) * 100, 2) : 0;

/* -----------------------------
   BOUNCE RATE
--------------------------------*/
$bounce_rate = $total_views ? round((($total_views - $total_starts) / $total_views) * 100, 2) : 0;


/* -----------------------------
   AVG TIME CALCULATION
--------------------------------*/

$times = $wpdb->get_results("
    SELECT usertimetakes
    FROM $submissions_table
    WHERE STR_TO_DATE(currentdate,'%M %e, %Y, %h:%i %p')
    BETWEEN '$start' AND '$end'
");

$total_seconds = 0;
$count = 0;

foreach($times as $row){
    
    $time = json_decode(stripslashes($row->usertimetakes), true);

    if(!$time) continue;

    $seconds =
        ($time['days'] * 86400) +
        ($time['hours'] * 3600) +
        ($time['minute'] * 60) +
        ($time['second']);

    $total_seconds += $seconds;
    $count++;
}

$avg_seconds = $count ? $total_seconds / $count : 0;
$avg_seconds = (int) round($avg_seconds);
$minutes = floor($avg_seconds / 60);
$seconds = $avg_seconds % 60;

$avg_time_display = $minutes."m ".$seconds."s";

?>



<div class="vform-dashboard">

    <div class="vform-card">
        <div class="label">Views 
            <svg width="20px" height="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="12" cy="12" r="3.5" stroke="#222222"/>
            <path d="M20.188 10.9343C20.5762 11.4056 20.7703 11.6412 20.7703 12C20.7703 12.3588 20.5762 12.5944 20.188 13.0657C18.7679 14.7899 15.6357 18 12 18C8.36427 18 5.23206 14.7899 3.81197 13.0657C3.42381 12.5944 3.22973 12.3588 3.22973 12C3.22973 11.6412 3.42381 11.4056 3.81197 10.9343C5.23206 9.21014 8.36427 6 12 6C15.6357 6 18.7679 9.21014 20.188 10.9343Z" stroke="#222222"/>
            </svg>
        </div>
        <div class="value"><?php echo number_format($total_views); ?></div>
    </div>

    <div class="vform-card">
        <div class="label">
             
            <div class="label-tooltip" data-tooltip="The number of users who began filling out the form after viewing it. These users interacted with at least one field in the form, even if they did not submit it.">
                Starts
                <svg width="15px" height="15px" viewBox="-0.5 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M12 21.5C17.1086 21.5 21.25 17.3586 21.25 12.25C21.25 7.14137 17.1086 3 12 3C6.89137 3 2.75 7.14137 2.75 12.25C2.75 17.3586 6.89137 21.5 12 21.5Z" stroke="#000000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M12.9309 8.15005C12.9256 8.39231 12.825 8.62272 12.6509 8.79123C12.4767 8.95974 12.2431 9.05271 12.0008 9.05002C11.8242 9.04413 11.6533 8.98641 11.5093 8.884C11.3652 8.7816 11.2546 8.63903 11.1911 8.47415C11.1275 8.30927 11.1139 8.12932 11.152 7.95675C11.19 7.78419 11.278 7.6267 11.405 7.50381C11.532 7.38093 11.6923 7.29814 11.866 7.26578C12.0397 7.23341 12.2192 7.25289 12.3819 7.32181C12.5446 7.39072 12.6834 7.506 12.781 7.65329C12.8787 7.80057 12.9308 7.97335 12.9309 8.15005ZM11.2909 16.5301V11.1501C11.2882 11.0556 11.3046 10.9615 11.3392 10.8736C11.3738 10.7857 11.4258 10.7057 11.4922 10.6385C11.5585 10.5712 11.6378 10.518 11.7252 10.4822C11.8126 10.4464 11.9064 10.4286 12.0008 10.43C12.094 10.4299 12.1863 10.4487 12.272 10.4853C12.3577 10.5218 12.4352 10.5753 12.4997 10.6426C12.5642 10.7099 12.6143 10.7895 12.6472 10.8767C12.6801 10.9639 12.6949 11.0569 12.6908 11.1501V16.5301C12.6908 16.622 12.6727 16.713 12.6376 16.7979C12.6024 16.8828 12.5508 16.96 12.4858 17.025C12.4208 17.09 12.3437 17.1415 12.2588 17.1767C12.1738 17.2119 12.0828 17.23 11.9909 17.23C11.899 17.23 11.8079 17.2119 11.723 17.1767C11.6381 17.1415 11.5609 17.09 11.4959 17.025C11.4309 16.96 11.3793 16.8828 11.3442 16.7979C11.309 16.713 11.2909 16.622 11.2909 16.5301Z" fill="#000000"/>
                    </svg>
            </div>

            
            <svg width="20px" height="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M16.6582 9.28638C18.098 10.1862 18.8178 10.6361 19.0647 11.2122C19.2803 11.7152 19.2803 12.2847 19.0647 12.7878C18.8178 13.3638 18.098 13.8137 16.6582 14.7136L9.896 18.94C8.29805 19.9387 7.49907 20.4381 6.83973 20.385C6.26501 20.3388 5.73818 20.0469 5.3944 19.584C5 19.053 5 18.1108 5 16.2264V7.77357C5 5.88919 5 4.94701 5.3944 4.41598C5.73818 3.9531 6.26501 3.66111 6.83973 3.6149C7.49907 3.5619 8.29805 4.06126 9.896 5.05998L16.6582 9.28638Z" stroke="#000000" stroke-width="2" stroke-linejoin="round"/>
            </svg>
            

        </div>
        <div class="value"><?php echo number_format($total_starts); ?></div>
    </div>

    <div class="vform-card">
        <div class="label">Submissions
            <svg width="20px" height="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M19 14C21.2091 14 23 16 23 17.5C23 18.3284 22.3284 19 21.5 19H21M17 11C18.6569 11 20 9.65685 20 8C20 6.34315 18.6569 5 17 5M5 14C2.79086 14 1 16 1 17.5C1 18.3284 1.67157 19 2.5 19H3M7 11C5.34315 11 4 9.65685 4 8C4 6.34315 5.34315 5 7 5M16.5 19H7.5C6.67157 19 6 18.3284 6 17.5C6 15 9 14 12 14C15 14 18 15 18 17.5C18 18.3284 17.3284 19 16.5 19ZM15 8C15 9.65685 13.6569 11 12 11C10.3431 11 9 9.65685 9 8C9 6.34315 10.3431 5 12 5C13.6569 5 15 6.34315 15 8Z" stroke="#000000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
        </div>
        <div class="value"><?php echo number_format($total_submissions); ?></div>
    </div>

    <div class="vform-card">
        <div class="label">Completion Rate
            <svg width="18px" height="18px" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path fill="#000000" d="M512 896a384 384 0 1 0 0-768 384 384 0 0 0 0 768zm0 64a448 448 0 1 1 0-896 448 448 0 0 1 0 896z"/><path fill="#000000" d="M745.344 361.344a32 32 0 0 1 45.312 45.312l-288 288a32 32 0 0 1-45.312 0l-160-160a32 32 0 1 1 45.312-45.312L480 626.752l265.344-265.408z"/></svg>
        </div>
        <div class="value"><?php echo $completion_rate; ?>%</div>
    </div>

    <div class="vform-card">
        <div class="label">Avg. Time
            <svg width="20px" height="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M12 21C16.9706 21 21 16.9706 21 12C21 7.02944 16.9706 3 12 3C7.02944 3 3 7.02944 3 12C3 16.9706 7.02944 21 12 21Z" stroke="#000000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M12 6V12" stroke="#000000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M16.24 16.24L12 12" stroke="#000000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
        </div>
        <div class="value"><?php echo $avg_time_display; ?></div>
        <div class="small">per completion</div>
    </div>

    <div class="vform-card">
        <div class="label">Bounce Rate
            <svg fill="#000000" width="18px" height="18px" viewBox="0 0 24 24" id="down-right" data-name="Flat Line" xmlns="http://www.w3.org/2000/svg" class="icon flat-line"><line id="primary" x1="18.36" y1="18.36" x2="5" y2="5" style="fill: none; stroke: rgb(0, 0, 0); stroke-linecap: round; stroke-linejoin: round; stroke-width: 2;"></line><polyline id="primary-2" data-name="primary" points="19 9 19 19 9.1 19" style="fill: none; stroke: rgb(0, 0, 0); stroke-linecap: round; stroke-linejoin: round; stroke-width: 2;"></polyline></svg>
        </div>
        <div class="value"><?php echo $bounce_rate; ?>%</div>
        <div class="small">viewed, didn't submit</div>
    </div>

</div>


<div class="vform-filter-bar">

    <select id="range_filter">
        <option value="7" <?php selected($range,'7'); ?>>Last 7 days</option>
        <option value="30" <?php selected($range,'30'); ?>>Last 30 days</option>
        <option value="90" <?php selected($range,'90'); ?>>Last 90 days</option>
        <option value="custom" <?php selected($range,'custom'); ?>>Custom Range</option>
    </select>

    <div class="date-range" id="customRange">

    <input type="date" id="start_date" value="<?php echo esc_attr($start_date); ?>">
    <span>—</span>
    <input type="date" id="end_date" value="<?php echo esc_attr($end_date); ?>">

    <button id="applyFilter" class="button button-primary">Apply</button>

    </div>

</div>

<style>

.vform-dashboard{
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(187px, 1fr));
    gap: 20px;
    margin-top: 25px;
    margin-right: 20px;
}

.vform-card{
background:#fff;
border:1px solid #e5e7eb;
border-radius:12px;
padding:24px;
box-shadow:0 3px 10px rgba(0,0,0,0.05);
transition:all .25s ease;
}

.vform-card:hover{
transform:translateY(-4px);
box-shadow:0 10px 20px rgba(0,0,0,0.08);
}

.vform-card .label{
font-size:14px;
color:#6b7280;
    display: flex;
    justify-content: space-between;
margin-bottom:8px;
}

.vform-card  .value{
font-size:34px;
font-weight:700;
color:#111827;
    margin-top: 20px;
}

.vform-card .small{
font-size:13px;
color:#9ca3af;
margin-top:6px;
}

</style>


<script>

const rangeSelect = document.getElementById("range_filter");
const customRange = document.getElementById("customRange");

function toggleCustomRange(){

    if(rangeSelect.value === "custom"){
        customRange.style.display = "flex";
    }else{
        customRange.style.display = "none";
    }

}

toggleCustomRange();

rangeSelect.addEventListener("change", function(){

    const range = this.value;
    let url = new URL(window.location.href);

    if(range === "custom"){

        customRange.style.display = "flex";

    }else{

        url.searchParams.set("range", range);

        // remove custom dates
        url.searchParams.delete("start_date");
        url.searchParams.delete("end_date");

        window.location = url;

    }

});

document.getElementById("applyFilter").addEventListener("click",function(){

    const start = document.getElementById("start_date").value;
    const end   = document.getElementById("end_date").value;

    if(!start || !end){
        alert("Please select both dates");
        return;
    }

    let url = new URL(window.location.href);

    url.searchParams.set("range","custom");
    url.searchParams.set("start_date",start);
    url.searchParams.set("end_date",end);

    window.location = url;

});


</script>
<style>
.vform-filter-bar{
display:flex;
gap:15px;
align-items:center;
    margin: 20px 20px;
    justify-content: flex-end;
}

.vform-filter-bar select{
padding:8px 12px;
border:1px solid #d1d5db;
border-radius:8px;
width: 145px;
}

.date-range{
display:none;
gap:10px;
align-items:center;
}

.date-range input{
padding:6px 10px;
border:1px solid #d1d5db;
border-radius:8px;
}

/* tooltip */
.label-tooltip {
    position: relative;
    display: inline-block;
    color: #555;
    cursor: default;
    margin-bottom: 5px;
}

/* Tooltip using ::after pseudo-element */
.label-tooltip::after {
    content: attr(data-tooltip); /* get tooltip text from data attribute */
    visibility: hidden;
    opacity: 0;
    width: 220px; /* adjust as needed */
    background-color: #333;
    color: #fff;
    text-align: left;
    padding: 8px;
    border-radius: 6px;
    font-size: 12px;
    line-height: 1.4;

    /* position above label */
    position: absolute;
    bottom: 125%; 
    left: 50%;
    transform: translateX(-50%);
    z-index: 10;

    /* small arrow */
    pointer-events: none;
    transition: opacity 0.3s;
}

/* Tooltip arrow */
.label-tooltip::before {
    content: "";
    position: absolute;
    bottom: 115%; /* slightly above the element */
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: #333 transparent transparent transparent;
    opacity: 0;
    transition: opacity 0.3s;
}

/* Show tooltip on hover */
.label-tooltip:hover::after,
.label-tooltip:hover::before {
    visibility: visible;
    opacity: 1;
}
</style>