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

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

require_once 'config.php';
require_once 'payroll/includes/Mailer.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: attendance.php");
    exit;
}

$recipientEmail = filter_input(INPUT_POST, 'recipient_email', FILTER_VALIDATE_EMAIL);
$selectedDate   = $_POST['date'] ?? date('Y-m-d');
$search         = $_POST['search'] ?? "";

if (!$recipientEmail) {
    header("Location: attendance.php?date=" . urlencode($selectedDate) . "&search=" . urlencode($search) . "&mail_status=invalid");
    exit;
}

// 1. Fetch Attendance Data for Selected Date/Filter
$_GET['date']   = $selectedDate;
$_GET['search'] = $search;

require_once 'attendance_script.php'; 

// 2. Build HTML Attendance Table Report
$formattedDate = date('d M Y', strtotime($selectedDate));
$totalRecords  = count($attendance);

$tableRows = '';
if (empty($attendance)) {
    $tableRows = '<tr><td colspan="6" style="padding:16px; text-align:center; color:#64748b; font-size:12px;">No attendance logs found for this query.</td></tr>';
} else {
    foreach ($attendance as $name => $data) {
        $shifts = $data['shifts'] ?? [];
        foreach ($shifts as $shift) {
            $shiftName = htmlspecialchars($data['shift_name'] ?? 'No Shift');
            $checkIn   = $shift['check_in'] ?? "—";
            $checkOut  = $shift['check_out'] ?? "—";
            $hours     = $shift['hours'] ?? 0;

            // Determine Status Label
            if (!empty($shift['worked_ph']))       { $status = 'Worked on PH'; $color = '#6b21a8'; $bg = '#f3e8ff'; }
            elseif (!empty($shift['late']))         { $status = 'Late Arrival'; $color = '#78350f'; $bg = '#fef3c7'; }
            elseif (!empty($shift['early']))        { $status = 'Early Leave';  $color = '#7c2d12'; $bg = '#ffedd5'; }
            elseif (!empty($shift['check_in']) && !empty($shift['check_out'])) { $status = 'Present'; $color = '#065f46'; $bg = '#d1fae5'; }
            elseif (!empty($shift['leave_pending'])){ $status = 'Leave Pending'; $color = '#92400e'; $bg = '#fef3c7'; }
            elseif (!empty($shift['leave']))        { $status = htmlspecialchars($shift['leave']); $color = '#1e1b4b'; $bg = '#e0e7ff'; }
            elseif (!empty($shift['holiday']))      { $status = 'Public Holiday'; $color = '#581c87'; $bg = '#f3e8ff'; }
            elseif (!empty($shift['off_day']))      { $status = 'Day Off';      $color = '#334155'; $bg = '#f1f5f9'; }
            elseif (!empty($shift['not_resumed']))  { $status = 'Not Resumed';  $color = '#3730a3'; $bg = '#e0e7ff'; }
            elseif (!empty($shift['absent']))       { $status = 'Absent';       $color = '#881337'; $bg = '#ffe4e6'; }
            else                                     { $status = 'Incomplete';   $color = '#334155'; $bg = '#f1f5f9'; }

            $tableRows .= "
            <tr style='border-bottom:1px solid #e2e8f0;'>
                <td style='padding:10px; font-weight:bold; color:#0f172a; font-size:12px;'>" . htmlspecialchars($name) . "</td>
                <td style='padding:10px; text-align:center; font-size:11px; color:#334155;'>{$shiftName}</td>
                <td style='padding:10px; text-align:center; font-family:monospace; font-size:11px; color:#334155;'>{$checkIn}</td>
                <td style='padding:10px; text-align:center; font-family:monospace; font-size:11px; color:#334155;'>{$checkOut}</td>
                <td style='padding:10px; text-align:center; font-family:monospace; font-size:11px; color:#047857; font-weight:bold;'>{$hours} hrs</td>
                <td style='padding:10px; text-align:center;'>
                    <span style='background:{$bg}; color:{$color}; padding:3px 8px; border-radius:4px; font-weight:bold; font-size:10px; display:inline-block;'>{$status}</span>
                </td>
            </tr>";
        }
    }
}

$htmlBody = "
<div style='font-family: Arial, sans-serif; color:#1e293b; max-width:680px; margin:auto;'>
    <div style='background:#0f172a; padding:20px; border-radius:8px 8px 0 0;'>
        <h2 style='color:#ffffff; margin:0; font-size:16px;'>System Attendance Summary Report</h2>
        <p style='color:#94a3b8; margin:4px 0 0 0; font-size:12px;'>Evaluation Date: <strong>{$formattedDate}</strong> | Total Logs: <strong>{$totalRecords}</strong></p>
    </div>
    <div style='border:1px solid #e2e8f0; border-top:0; padding:20px; border-radius:0 0 8px 8px;'>
        <p style='font-size:13px; color:#334155;'>Here is the system-generated daily attendance verification log report:</p>
        <table style='width:100%; border-collapse:collapse; margin:16px 0;'>
            <thead>
                <tr style='background:#f8fafc; text-align:left; font-size:10px; text-transform:uppercase; color:#64748b; border-bottom:2px solid #e2e8f0;'>
                    <th style='padding:10px;'>Employee Name</th>
                    <th style='padding:10px; text-align:center;'>Shift</th>
                    <th style='padding:10px; text-align:center;'>Check-In</th>
                    <th style='padding:10px; text-align:center;'>Check-Out</th>
                    <th style='padding:10px; text-align:center;'>Hours</th>
                    <th style='padding:10px; text-align:center;'>Status</th>
                </tr>
            </thead>
            <tbody>
                {$tableRows}
            </tbody>
        </table>
        <p style='font-size:11px; color:#94a3b8; margin-top:20px;'>Report generated automatically by HR Engine • Core System Architecture.</p>
    </div>
</div>";

// 3. Send Email
try {
    $mailer = new Mailer($conn);
    $subject = "Attendance Log Report - " . $formattedDate;
    $res = $mailer->send($recipientEmail, 'HR Manager / Recipient', $subject, $htmlBody);

    if ($res['success']) {
        header("Location: attendance.php?date=" . urlencode($selectedDate) . "&search=" . urlencode($search) . "&mail_status=success");
    } else {
        header("Location: attendance.php?date=" . urlencode($selectedDate) . "&search=" . urlencode($search) . "&mail_status=error&error=" . urlencode($res['error']));
    }
} catch (Exception $e) {
    header("Location: attendance.php?date=" . urlencode($selectedDate) . "&search=" . urlencode($search) . "&mail_status=error&error=" . urlencode($e->getMessage()));
}
exit;