<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

$conn = new mysqli("localhost", "webcreatah_anl_video", "72(xvI2s_Aw=NkH=", "webcreatah_anl_video");

if ($conn->connect_error) {
    die("DB Connection failed");
}

$date = date("Y-m-d");

if (date('w') == 0) {
    exit("Today is Sunday - Cron Skipped");
}

if (date('w') == 6) {

    $day = date('d');
    $week = ceil($day / 7);

    if ($week == 2 || $week == 4) {
        exit("Today is $week Saturday - Cron Skipped");
    }
}

$holidayCheck = "SELECT COUNT(*) as total 
                 FROM holiday_calendar 
                 WHERE holiday_date = '$date' 
                 AND del_i = 0";

$holidayResult = $conn->query($holidayCheck);
$holidayRow = $holidayResult->fetch_assoc();

if ($holidayRow['total'] > 0) {
    exit("Today is Holiday - Cron Skipped");
}

$webhook = "https://cliq.zoho.com/api/v2/channelsbyname/adminhub/message?zapikey=1001.12bed28614fde408c2b6f06c9bf5260f.610c064f960fa781e2dd846bcb2562bc";

$countQuery = "SELECT COUNT(*) as total FROM meter_readings WHERE DATE(created_at)=CURDATE()";
$countResult = $conn->query($countQuery);
$countRow = $countResult->fetch_assoc();
$count = $countRow['total'];


if ($count > 0) {

    $sql = "SELECT mr.id, mr.units, mr.photo_path, us.* 
            FROM meter_readings AS mr 
            LEFT JOIN users AS us ON mr.user_id = us.id 
            WHERE DATE(mr.created_at) = CURDATE()   
            AND mr.cron_notified = 0 
            ORDER BY mr.id DESC LIMIT 1";

    $result = $conn->query($sql);

    if ($result->num_rows > 0) {

        $row = $result->fetch_assoc();

        $id = $row['id'];
        $units = $row['units'];
        $image = $row['photo_path'];
        $name = $row['name'];

        $image_url = "https://anl-video.companyonline.in/uploads/readings/" . $image;

        $text = "Hello @admin,\n\n"
              . "This is an automated update regarding today's meter readings.\n\n"
              . "Meter reading recorded successfully\n"
              . "Units Consumed: $units\n\n"
              . "Submitted By: $name";

        $payload = [
            "text" => $text,
            "card" => [
                "title" => "$date Reading Details",
                "thumbnail" => $image_url,
                "theme" => "modern-inline"
            ]
        ];

        sendToCliq($webhook, $payload);

        $conn->query("UPDATE meter_readings SET cron_notified=1 WHERE id=$id");
    }
}

else {

    $text = "Hello @Sabari V,\n\n"
          . "This is an automated update regarding today's meter readings.\n\n"
          . "No meter readings have been recorded today\n\n"
          . "Date: $date\n\n"
          . "Kindly check and take necessary action.\n\n"
          . "Regards,\nSystem Notification";

    sendToCliq($webhook, ["text" => $text]);
}

function sendToCliq($url, $data) {

    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);

    if(curl_errno($ch)){
        echo "CURL ERROR: " . curl_error($ch);
    }

    curl_close($ch);
}

$conn->close();

?>