<?php
include_once('../components/connect.php');

$date = date('Y-m-d');
$selected_date1 = explode('-', $date);
$month = $selected_date1[0];
$day = $selected_date1[1];
$year = $selected_date1[2];

$unix_time = mktime(0, 0, 0, $month, $day, $year);


$monday_p = date("m-d-Y", strtotime('monday last week', $unix_time));
$monday = date("m-d-Y", strtotime('monday this week', $unix_time));

$to = 'vaibhavnanda2000@gmail.com';
$subject = 'Subject: Daycare Invoice for the weeks of ' . $monday_p . ' and ' . $monday;
$headers = 'From: vaibhavnanda2000@gmail.com';

$sql = "SELECT * FROM children_details WHERE is_invoiced = 0 AND invoice_due = '$date'";
$resp['success'] = false;

$result = mysqli_query($conn, $sql);


if (mysqli_num_rows($result) > 0) 
{
    $message = 'Hi ' . $row_result['mother_name'] . 'and' . $row_result['father_name'] . ',
                Please find attached the daycare invoice for last two weeks.

                Thanks and Regards
                Rajeev Bharol
                Logistics and accounts receivable
                Kool Kids Day Care
                1030 Cheyenne Drive
                Gilroy CA 95020
                510 565 8260 (c)
                510 722 2223 (f)';
    $file = '../invoices/invoice_' . $row_result['child_id'] . '' . $row_result['invoice_due']  . '.pdf';

    $child_id = $row_result['child_id'];
    if (mail($to, $subject, $message, $headers, $file)) {
        
        $sent = 1;
        $sql = "UPDATE children_details SET is_invoiced = '$sent' WHERE child_id = '$child_id'";
        $result = mysqli_query($conn, $sql);
        if ($result)
        {
            $resp['success'] = true;
            $resp['msg'] = 'Email sent successfully!';
        }
        else
        {
            $resp['msg'] = 'Something went wrong!';
        }
    } else {
        $resp['msg'] = "Email sending failed";
    }
}
else
{
    $resp['msg'] = 'No invoices to be sent!';
}

echo json_encode($resp);
?>