<?php
// timesheet_notify.php

require_once '../../config/config.php';         // Your DB connection
require_once '../../vendor/autoload.php';     // PHPMailer wrapper

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

function generateMissingTimesheetEmailToRM($rmName, $entries)
{
    $rows = '';
    foreach ($entries as $entry) {
        $rows .= "<tr>
            <td>{$entry['emp_name']}</td>
            <td>{$entry['emp_id']}</td>
            <td>{$entry['dept']}</td>
            <td>{$entry['sub_dept']}</td>
            <td>{$entry['date']}</td>
        </tr>";
    }

    return "
    <html>
    <body>
        <p>Dear {$rmName},</p>
        <p>We would like to inform you that the following employee(s) reporting to you have not submitted their timesheets as of the indicated date:</p>
        <h4>Pending Timesheets:</h4>
        <table border='1' cellpadding='5' cellspacing='0'>
            <tr><th>Employee Name</th><th>Employee ID</th><th>Department</th><th>Sub Department</th><th>Due Date</th></tr>
            {$rows}
        </table>
        <p>Please take the necessary steps to follow up and ensure the timesheets are submitted promptly.</p>
        <p>If you require assistance, feel free to reach out to HR or IT support.</p>
        <br>
        <p>Best Regards,<br><i>Timesheet Monitoring System<br>[Company Name]</i></p>
    </body>
    </html>";
}

function generateApprovalReminderEmailToRM($rmName, $currentDate, $entries)
{
    $rows = '';
    foreach ($entries as $entry) {
        $rows .= "<tr>
            <td>{$entry['emp_name']}</td>
            <td>{$entry['emp_id']}</td>
            <td>{$entry['dept']}</td>
            <td>{$entry['sub_dept']}</td>
            <td>{$entry['date']}</td>
        </tr>";
    }

    return "
    <html>
    <body>
        <p>Dear {$rmName},</p>
        <p>This is a gentle reminder that you have pending timesheets submitted by your team members awaiting your review and approval. As of <b>{$currentDate}</b>, these have been pending for over 24 hours.</p>
        <h4>Pending Timesheet Approvals</h4>
        <table border='1' cellpadding='5' cellspacing='0'>
            <tr><th>Employee Name</th><th>Employee ID</th><th>Department</th><th>Sub Department</th><th>Submission Date</th></tr>
            {$rows}
        </table>
        <p>Please log in to the Timesheet Management Portal to take the necessary actions.</p>
        <p><b>Access the Timesheet Portal:</b> <a href='[Portal Link]'>Click here to review timesheets</a></p>
        <p>Thank you for your cooperation.<br><i>Timesheet Compliance System</i><br>[Company Name]</p>
    </body>
    </html>";
}


function generateEscalationEmailToHOD($hodName, $entries)
{
    $rows = '';
    foreach ($entries as $entry) {
        $rows .= "<tr>
            <td>{$entry['emp_name']}</td>
            <td>{$entry['emp_id']}</td>
            <td>{$entry['dept']}</td>
            <td>{$entry['sub_dept']}</td>
            <td>{$entry['date']}</td>
            <td>{$entry['rm_name']}</td>
        </tr>";
    }

    return "
    <html>
    <body>
        <p>Dear {$hodName},</p>
        <p>This is to inform you that one or more timesheets submitted by executives in your department have not been approved within the required 48-hour window by their Reporting Managers.</p>
        <h4>Details of Escalated Timesheets</h4>
        <table border='1' cellpadding='5' cellspacing='0'>
            <tr><th>Employee Name</th><th>Employee ID</th><th>Department</th><th>Subdepartment</th><th>Submission Date</th><th>Reporting Manager</th></tr>
            {$rows}
        </table>
        <p>We kindly request you to review the above cases and take appropriate action to ensure the pending approvals are completed.</p>
        <p><b>Access the Timesheet Dashboard:</b> <a href='[Link]'>Click here to review</a></p>
        <br>
        <p>Thank you for your prompt attention to this matter.</p>
        <p>Best regards,<br><i>Timesheet Compliance System<br>[Company Name]</i></p>
    </body>
    </html>";
}



function sendEmail($type, $recipientEmail, $recipientName, $entries, $date = null)
{
    $mail = new PHPMailer(true);

    try {
        // Email setup
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'wildnettesting44@gmail.com';
        $mail->Password = 'duep vjxl qdhe viok';    // SMTP password
        $mail->SMTPSecure = 'tls';                    // Encryption (tls or ssl)
        $mail->Port = 587;                      // TCP port

        $mail->setFrom('wildnettesting44@gmail.com', 'Timesheet Compliance System');
        $mail->addAddress($recipientEmail, $recipientName);
        $mail->isHTML(true);

        // Subject & Body based on type
        switch ($type) {
            case 'missing_timesheet':
                $mail->Subject = 'Missing Timesheet Entries - Action Required';
                $mail->Body = generateMissingTimesheetEmailToRM($recipientName, $entries);
                break;

            case 'approval_pending':
                $mail->Subject = 'Pending Timesheet Approvals';
                $mail->Body = generateApprovalReminderEmailToRM($recipientName, $date ?? date('Y-m-d'), $entries);
                break;

            case 'escalation_to_hod':
                $mail->Subject = 'Escalated Timesheet Approvals';
                $mail->Body = generateEscalationEmailToHOD($recipientName, $entries);
                break;

            default:
                throw new Exception("Invalid email type: $type");
        }

        $mail->send();
        return true;

    } catch (Exception $e) {
        error_log("Email failed: " . $mail->ErrorInfo);
        return false;
    }
}


// Get all employees
function getAllEmployees($conn)
{
    $result = $conn->query("SELECT * FROM employee");
    return $result->fetch_all(MYSQLI_ASSOC);
}

// Get all task entries for an employee on a given date
function getTasksForDate($conn, $empId, $date)
{
    $stmt = $conn->prepare("SELECT * FROM task WHERE emp_id = ? AND date = ?");
    $stmt->bind_param("is", $empId, $date);
    $stmt->execute();
    return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}

// Check if an email has already been sent
function emailAlreadySent($conn, $empId, $date, $type)
{
    $stmt = $conn->prepare("SELECT id FROM email_logs WHERE emp_id = ? AND date = ? AND type = ?");
    $stmt->bind_param("iss", $empId, $date, $type);
    $stmt->execute();
    $stmt->store_result();
    return $stmt->num_rows > 0;
}

// Log email
function logEmail($conn, $empId, $date, $type, $recipient)
{
    $stmt = $conn->prepare("INSERT INTO email_logs (emp_id, date, type, recipient, sent_at) VALUES (?, ?, ?, ?, NOW())");
    $stmt->bind_param("isss", $empId, $date, $type, $recipient);
    $stmt->execute();
}

// Send email (uses your mailer.php)
// function sendEmail($to, $subject, $body)
// {
//     sendMail($to, $subject, $body); // Assumes sendMail() from your mailer.php
// }

// Main logic
$employees = getAllEmployees($conn);
$today = new DateTime();

foreach ($employees as $emp) {
    $empId = $emp['id'];
    $empEmail = $emp['email'];
    $rmEmail = $emp['rm_email'];
    $hodEmail = $emp['hod_email'];
    $empName = $emp['name'];

    for ($i = 1; $i <= 3; $i++) {
        $date = clone $today;
        $date->modify("-$i days");
        $dateStr = $date->format('Y-m-d');

        $tasks = getTasksForDate($conn, $empId, $dateStr);

        // 1. Missing Timesheet (send on D+1 i.e. today 1 a.m.)
        if (empty($tasks)) {
            if (!emailAlreadySent($conn, $empId, $dateStr, 'missing')) {
                $subject = "Timesheet Missing for {$dateStr}";
                $body = "Timesheet for $dateStr is missing. Please fill it as soon as possible.";
                sendEmail($empEmail, $subject, $body);
                sendEmail($rmEmail, $subject, "Your team member $empName has not filled their timesheet for $dateStr.");
                logEmail($conn, $empId, $dateStr, 'missing', $empEmail);
                logEmail($conn, $empId, $dateStr, 'missing', $rmEmail);
            }
            continue;
        }

        // Determine if all tasks are approved
        $allApproved = array_reduce($tasks, fn($carry, $task) => $carry && $task['status'] == 1, true);

        // 2. Pending Approval Reminder to RM (on D+2)
        if (!$allApproved && $i >= 2) {
            if (!emailAlreadySent($conn, $empId, $dateStr, 'approval_reminder')) {
                $subject = "Timesheet Approval Reminder for $dateStr";
                $body = "Please review and approve the timesheet submitted by $empName for $dateStr.";
                sendEmail($rmEmail, $subject, $body);
                logEmail($conn, $empId, $dateStr, 'approval_reminder', $rmEmail);
            }
        }

        // 3. Escalation to HOD (on D+4)
        if (!$allApproved && $i >= 3) {
            if (!emailAlreadySent($conn, $empId, $dateStr, 'escalation')) {
                $subject = "Escalation: Timesheet Pending for $empName";
                $body = "Timesheet for $empName on $dateStr is still pending approval. Please look into this matter.";
                sendEmail($hodEmail, $subject, $body);
                logEmail($conn, $empId, $dateStr, 'escalation', $hodEmail);
            }
        }
    }
}
