<?php
// ----------------- DEBUG / ERROR REPORTING -----------------
// error_reporting(E_ALL);
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);

session_start();
include 'branch_connection.php';

require 'vendor/autoload.php'; // PHPMailer

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

// ----------------- TODAY -----------------
$today = date("Y-m-d");

// ----------------- HELPER FUNCTION (Beautified Table) -----------------
function getTableHTML($conn, $table, $title, $columns, $where = "") {
    global $today;

    $sql = "SELECT * FROM $table WHERE DATE(created_at)='$today'";
    if($where != "") $sql .= " AND $where";

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

    if(mysqli_num_rows($result) == 0) return "";

    $html = "<h3 style='font-family: Arial, sans-serif; color: #333;'>$title</h3>";
    $html .= "<table style='border-collapse: collapse; width: 100%; font-family: Arial, sans-serif; margin-bottom: 20px;'>";
    $html .= "<tr style='background-color: #4CAF50; color: white;'>";

    // Table headers
    foreach($columns as $col){
        $html .= "<th style='border: 1px solid #ddd; padding: 8px; text-align: left;'>$col</th>";
    }
    $html .= "</tr>";

    // Table rows
    $row_count = 0;
    while($row = mysqli_fetch_assoc($result)){
        $bgColor = ($row_count % 2 == 0) ? "#f9f9f9" : "#ffffff";
        $html .= "<tr style='background-color: $bgColor;'>";
        foreach($columns as $col){
            $html .= "<td style='border: 1px solid #ddd; padding: 8px;'>".htmlspecialchars($row[$col])."</td>";
        }
        $html .= "</tr>";
        $row_count++;
    }

    $html .= "</table>";
    return $html;
}

// ----------------- BUILD EMAIL BODY -----------------
$body  = "<div style='font-family: Arial, sans-serif; color: #333;'>";
$body .= "<h2 style='color: #2E86C1;'>Today's Task Updates ($today)</h2>";
$body .= "<p>Here are the updates for today. Please review the details below:</p>";

// Existing tables
$body .= getTableHTML($conn, "marketing_order", "Marketing Order Updates", 
          ["order_id","customer_name","mobile","order_amt","status"]);

$body .= getTableHTML($conn, "tb_positiveleads", "Positive Leads Updates", 
          ["customer_name","mobile","status","category"]);

$body .= getTableHTML($conn, "tb_leads", "Lead Updates", 
          ["customer_name","mobile","status","category"]);

$body .= getTableHTML($conn, "teledata", "Teledata Updates", 
          ["company_name","mobile","status"]);

// New: Proposals Table
$body .= getTableHTML($conn, "proposals", "Proposals Updates", 
          ["proposal_no","bdm","qtnby","details","total","discount","source","currency"]);

// If no updates at all
if(trim($body) == "<div style='font-family: Arial, sans-serif; color: #333;'><h2 style='color: #2E86C1;'>Today's Task Updates ($today)</h2><p>Here are the updates for today. Please review the details below:</p>"){
    $body .= "<p>No updates for today.</p>";
}

$body .= "<p style='margin-top:20px; font-size: 12px; color: #888;'>This is an automated email. Please do not reply.</p>";
$body .= "</div>";

// ----------------- PHPMailer CONFIG -----------------
$mail = new PHPMailer(true);

try {
    // SMTP settings
    $mail->isSMTP();
    $mail->Host       = 'smtp.gmail.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'rosecollections97@gmail.com'; // Your Gmail
    $mail->Password   = 'xxriaftnmltwyhbu'; // App Password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;

    // Recipients
    $mail->setFrom('rosecollections97@gmail.com', 'Daily Task Reports');
    $mail->addAddress('projects@programers.in'); // Receiver

    // Content
    $mail->isHTML(true);
    $mail->Subject = "Today's Task Updates - $today";
    $mail->Body    = $body;

    $mail->send();

    // ----------------- SUCCESS SWEETALERT -----------------
    echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        Swal.fire({
            icon: "success",
            title: "Mail Sent!",
            text: "Today\'s task updates have been sent successfully.",
            confirmButtonText: "OK"
        }).then(() => {
            window.location.href = "index.php";
        });
    </script>';

} catch (Exception $e) {
    // ----------------- ERROR SWEETALERT -----------------
    $error = addslashes($mail->ErrorInfo);
    echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        Swal.fire({
            icon: "error",
            title: "Mail Failed!",
            text: "'.$error.'",
            confirmButtonText: "OK"
        });
    </script>';
}
?>
