<?php
// daily_reports.php — sends scheduled task summaries via email and WhatsApp.
// This file is relocated outside of public_html and should be executed via CLI only.

// Enforce CLI-only execution: abort if run via a web request.
if (php_sapi_name() !== 'cli') {
    if (function_exists('http_response_code')) {
        http_response_code(403);
    }
    exit;
}

// Original notify.php — sends scheduled task summaries via email and WhatsApp
// Enhanced: HTML tables (dept + management), client before task, DMARC-friendly mail()
//           + Serial # column, and overdue rows highlighted in red.

// ===== Configuration =====
$DATA_FILE = dirname(__DIR__) . '/public_html/erp/erp_data.json';
$TZ        = 'Asia/Karachi';

// Department heads: update these values as needed
$heads = [
  'Tax'        => ['email' => 'usmanmunir@thebellcon.com',         'whatsapp' => '+923455206933'],
  'Corporate'  => ['email' => 'corporate@thebellcon.com',           'whatsapp' => '+923349154791'],
  'Audit'      => ['email' => 'assuranceandadvisory@thebellcon.com','whatsapp' => '+923095943445'],
  'Accounts'   => ['email' => 'accounts@thebellcon.com',            'whatsapp' => '+923421941016'],
  'Admin & HR' => ['email' => 'coord@thebellcon.com',               'whatsapp' => '+923230111444'],
  'Management' => ['email' => 'arshad@thebellcon.com',              'whatsapp' => '+923345127002'],
];

// Secondary partner (Partner 2)
$secondaryCc = 'aizaz@thebellcon.com';

// ===== Helper functions =====
function load_state($file) {
  if (!file_exists($file)) return ['clients' => [], 'users' => [], 'tasks' => []];
  $json = file_get_contents($file);
  $data = json_decode($json, true);
  return $data ?: ['clients' => [], 'users' => [], 'tasks' => []];
}

// Convert dd-mm-yy or yyyy-mm-dd to DateTime in the configured timezone
function parse_iso($iso, $tz) {
  if (!$iso) return null;
  try { return new DateTime($iso . ' 00:00:00', new DateTimeZone($tz)); }
  catch (Exception $e) { return null; }
}

// Prefer common client code/name fields on task; fallback to lookup in $clients by id
function get_client_label($task, $clients) {
  foreach (['client_code','client_short','client_tag','client'] as $k) {
    if (!empty($task[$k])) return $task[$k];
  }
  if (!empty($task['client_name'])) return $task['client_name'];

  $clientId = $task['client_id'] ?? $task['clientID'] ?? $task['clientId'] ?? null;
  if ($clientId && is_array($clients)) {
    foreach ($clients as $c) {
      if ((isset($c['id']) && $c['id'] == $clientId) ||
          (isset($c['client_id']) && $c['client_id'] == $clientId)) {
        if (!empty($c['code'])) return $c['code'];
        if (!empty($c['short'])) return $c['short'];
        if (!empty($c['tag'])) return $c['tag'];
        if (!empty($c['name'])) return $c['name'];
        if (!empty($c['client_name'])) return $c['client_name'];
      }
    }
  }
  return '';
}

function filter_tasks($tasks, $dept, $today, $period) {
  $result = [];
  $todayStart = clone $today; $todayStart->setTime(0,0,0);
  $todayEnd   = clone $today; $todayEnd->setTime(23,59,59);
  $startWeek  = clone $today; $startWeek->modify('monday this week'); $startWeek->setTime(0,0,0);
  $endWeek    = clone $startWeek; $endWeek->modify('+6 days')->setTime(23,59,59);
  $startMonth = new DateTime($today->format('Y-m-01'), $today->getTimezone()); $startMonth->setTime(0,0,0);
  $endMonth   = new DateTime($today->format('Y-m-t'),  $today->getTimezone()); $endMonth->setTime(23,59,59);

  foreach ($tasks as $t) {
    if ($dept && (($t['department'] ?? '') !== $dept)) continue;
    $due    = parse_iso($t['due_date']   ?? '', $today->getTimezone()->getName());
    $start  = parse_iso($t['start_date'] ?? '', $today->getTimezone()->getName());
    $status = $t['status'] ?? '';
    if (!$due) continue;

    $include = false;
    if ($period === 'day') {
      if ($due >= $todayStart && $due <= $todayEnd) $include = true;
      elseif ($due < $todayStart && $status !== 'Completed') $include = true;
      elseif ($start && $start >= $todayStart && $start <= $todayEnd) $include = true;
    } elseif ($period === 'week') {
      if ($due >= $startWeek && $due <= $endWeek) $include = true;
      elseif ($due < $startWeek && $status !== 'Completed') $include = true;
      elseif ($start && $start >= $startWeek && $start <= $endWeek) $include = true;
    } elseif ($period === 'month') {
      if ($due >= $startMonth && $due <= $endMonth) $include = true;
      elseif ($due < $startMonth && $status !== 'Completed') $include = true;
      elseif ($start && $start >= $startMonth && $start <= $endMonth) $include = true;
    }
    if ($include) $result[] = $t;
  }
  return $result;
}

// ---------- PLAIN TEXT (for dept heads & WhatsApp), with CLIENT BEFORE TASK ----------
function compose_message($title, $tasks, $clients = []) {
  if (empty($tasks)) return "$title\nNo tasks.";
  $msg = "$title\n";
  $i = 1;
  foreach ($tasks as $t) {
    $dept   = $t['department']       ?? '';
    $desc   = $t['task_description'] ?? ($t['description'] ?? '');
    $due    = $t['due_date']         ?? '';
    $status = $t['status']           ?? '';
    $client = get_client_label($t, $clients);
    $clientPart = $client ? $client . ' — ' : '';     // client BEFORE task
    $msg .= $i . ". " . $dept . " — " . $clientPart . $desc .
            " (Due: " . $due . ", Status: " . $status . ")\n";
    $i++;
  }
  return $msg;
}

// ---------- HTML helpers ----------
function e($s){ return htmlspecialchars((string)$s ?? '', ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }

function base_email_css() {
  return '
    <style>
      body { font-family: Arial, Helvetica, sans-serif; font-size:14px; color:#111; }
      h2 { margin:0 0 12px; font-size:18px; }
      h3 { margin:16px 0 8px; font-size:16px; }
      table { border-collapse: collapse; width: 100%; margin: 6px 0 18px; }
      th, td { border:1px solid #ddd; padding:8px; vertical-align: top; }
      th { background:#f4f6f8; text-align:left; }
      tr.overdue td { background:#fdecea; }           /* light red background */
      tr.overdue td:last-child { font-weight:600; }   /* emphasize Status */
      .muted { color:#666; font-size:12px; }
      .col-n { width:6%; }
      .col-client { width:22%; }
      .col-due { width:14%; }
      .col-status { width:16%; }
    </style>';
}

// ---------- HTML (for Department emails: table layout, client before task, SN + overdue color) ----------
function compose_dept_html($title, $deptName, $tasks, $clients = [], $today = null, $tz = 'Asia/Karachi') {
  $style = base_email_css();
  $html = "<!DOCTYPE html><html><head><meta charset='utf-8'>{$style}</head><body>";
  $html .= "<h2>" . e($title) . "</h2>";
  $html .= "<h3><strong>" . e($deptName) . "</strong></h3>";

  if (empty($tasks)) {
    $html .= "<p>No tasks.</p></body></html>";
    return $html;
  }

  // For overdue marking
  $today = $today ?: new DateTime('now', new DateTimeZone($tz));
  $todayStart = clone $today; $todayStart->setTime(0,0,0);

  $html .= "<table><thead><tr>
              <th class='col-n'>#</th>
              <th class='col-client'>Client</th>
              <th>Task</th>
              <th class='col-due'>Due</th>
              <th class='col-status'>Status</th>
            </tr></thead><tbody>";

  $i = 1;
  foreach ($tasks as $t) {
    $client = get_client_label($t, $clients);
    $desc   = $t['task_description'] ?? ($t['description'] ?? '');
    $dueStr = $t['due_date']         ?? '';
    $status = $t['status']           ?? '';

    $dueDT = parse_iso($dueStr, $today->getTimezone()->getName());
    $isOverdue = $dueDT && ($dueDT < $todayStart) && (strtolower($status) !== 'completed');

    $rowClass = $isOverdue ? " class='overdue'" : "";
    $html .= "<tr{$rowClass}>
                <td>" . e($i) . "</td>
                <td>" . e($client) . "</td>
                <td>" . e($desc) . "</td>
                <td>" . e($dueStr) . "</td>
                <td>" . e($status) . "</td>
              </tr>";
    $i++;
  }

  $html .= "</tbody></table>";
  $html .= "<p class='muted'>Auto-generated by Bellwether ERP</p></body></html>";
  return $html;
}

// ---------- HTML (for Management: grouped by dept, table layout, SN + overdue color) ----------
function compose_management_grouped_html($title, $tasks, $clients = [], $today = null, $tz = 'Asia/Karachi') {
  // group by department
  $byDept = [];
  foreach ($tasks as $t) {
    $d = $t['department'] ?? 'Unassigned';
    $byDept[$d][] = $t;
  }
  ksort($byDept, SORT_NATURAL | SORT_FLAG_CASE);

  $style = base_email_css();
  $html = "<!DOCTYPE html><html><head><meta charset='utf-8'>{$style}</head><body>";
  $html .= "<h2>" . e($title) . "</h2>";

  if (empty($tasks)) {
    $html .= "<p>No tasks.</p></body></html>";
    return $html;
  }

  // For overdue marking
  $today = $today ?: new DateTime('now', new DateTimeZone($tz));
  $todayStart = clone $today; $todayStart->setTime(0,0,0);

  foreach ($byDept as $dept => $list) {
    $html .= "<h3><strong>" . e($dept) . "</strong></h3>";
    $html .= "<table><thead><tr>
                <th class='col-n'>#</th>
                <th class='col-client'>Client</th>
                <th>Task</th>
                <th class='col-due'>Due</th>
                <th class='col-status'>Status</th>
              </tr></thead><tbody>";

    $i = 1;
    foreach ($list as $t) {
      $client = get_client_label($t, $clients);
      $desc   = $t['task_description'] ?? ($t['description'] ?? '');
      $dueStr = $t['due_date']         ?? '';
      $status = $t['status']           ?? '';

      $dueDT = parse_iso($dueStr, $today->getTimezone()->getName());
      $isOverdue = $dueDT && ($dueDT < $todayStart) && (strtolower($status) !== 'completed');

      $rowClass = $isOverdue ? " class='overdue'" : "";
      $html .= "<tr{$rowClass}>
                  <td>" . e($i) . "</td>
                  <td>" . e($client) . "</td>
                  <td>" . e($desc) . "</td>
                  <td>" . e($dueStr) . "</td>
                  <td>" . e($status) . "</td>
                </tr>";
      $i++;
    }
    $html .= "</tbody></table>";
  }

  $html .= "<p class='muted'>Auto-generated by Bellwether ERP</p></body></html>";
  return $html;
}

// Also provide a plain-text fallback for WhatsApp or clients that force text
function compose_management_grouped_text($title, $tasks, $clients = []) {
  if (empty($tasks)) return "$title\nNo tasks.";
  $byDept = [];
  foreach ($tasks as $t) {
    $d = $t['department'] ?? 'Unassigned';
    $byDept[$d][] = $t;
  }
  ksort($byDept, SORT_NATURAL | SORT_FLAG_CASE);

  $out = "$title\n";
  foreach ($byDept as $dept => $list) {
    $out .= "\n=== $dept ===\n";
    $i = 1;
    foreach ($list as $t) {
      $client = get_client_label($t, $clients);
      $desc   = $t['task_description'] ?? ($t['description'] ?? '');
      $due    = $t['due_date']         ?? '';
      $status = $t['status']           ?? '';
      $clientPart = $client ? $client . ' — ' : '';
      $out .= $i . ". " . $clientPart . $desc . " (Due: " . $due . ", Status: " . $status . ")\n";
      $i++;
    }
  }
  return $out;
}

// Send an email (supports HTML and envelope sender for DMARC alignment)
function send_email($to, $subject, $body, $cc = '', $isHtml = false, $envelopeFrom = 'bounce@thebellcon.com') {
  $headers = "From: coord@thebellcon.com\r\n";
  if ($cc) $headers .= "Cc: $cc\r\n";
  if ($isHtml) {
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=utf-8\r\n";
  } else {
    $headers .= "Content-Type: text/plain; charset=utf-8\r\n";
  }
  // Use -f to set Return-Path/envelope sender (helps DMARC/SPF alignment)
  $params = $envelopeFrom ? "-f $envelopeFrom" : "";
  return mail($to, $subject, $body, $headers, $params);
}

// Send a WhatsApp message via your existing API
function send_whatsapp($number, $message) {
  $apiUrl = 'https://www.thebellcon.com/whatsapp_api/send.php'; // placeholder
  $payload = ['number' => $number, 'message' => $message];
  $options = ['http' => [
      'header'  => "Content-Type: application/json\r\n",
      'method'  => 'POST',
      'content' => json_encode($payload),
  ]];
  $context = stream_context_create($options);
  @file_get_contents($apiUrl, false, $context);
}

// ===== Main logic =====
$state   = load_state($DATA_FILE);
$clients = $state['clients'] ?? [];
$tasks   = $state['tasks']   ?? [];

$tzObj = new DateTimeZone($TZ);
$today = new DateTime('now', $tzObj);
$dow   = (int)$today->format('N'); // 1=Mon
$dom   = (int)$today->format('j');

$sendDaily   = true;
$sendWeekly  = ($dow === 1); // Monday
$sendMonthly = ($dom === 1);

// Per-department emails & WhatsApp (HTML + text for WA)
foreach ($heads as $dept => $info) {
  if ($dept === 'Management') continue; // management handled separately

  if ($sendDaily) {
    $list = filter_tasks($tasks, $dept, $today, 'day');
    $html = compose_dept_html('Daily Tasks Summary', $dept, $list, $clients, $today, $TZ);
    $txt  = compose_message('Tasks for Today', $list, $clients);
    send_email($info['email'], "Daily Tasks Summary", $html, '', true); // HTML
    send_whatsapp($info['whatsapp'], $txt); // text
  }
  if ($sendWeekly) {
    $list = filter_tasks($tasks, $dept, $today, 'week');
    $html = compose_dept_html('Weekly Tasks Summary', $dept, $list, $clients, $today, $TZ);
    $txt  = compose_message('Tasks for This Week', $list, $clients);
    send_email($info['email'], "Weekly Tasks Summary", $html, '', true);
    send_whatsapp($info['whatsapp'], $txt);
  }
  if ($sendMonthly) {
    $list = filter_tasks($tasks, $dept, $today, 'month');
    $html = compose_dept_html('Monthly Tasks Summary', $dept, $list, $clients, $today, $TZ);
    $txt  = compose_message('Tasks for This Month', $list, $clients);
    send_email($info['email'], "Monthly Tasks Summary", $html, '', true);
    send_whatsapp($info['whatsapp'], $txt);
  }
}

// Management summaries (HTML email grouped by department + text for WhatsApp)
$managementContacts = [
  ['email' => $heads['Management']['email'], 'whatsapp' => $heads['Management']['whatsapp']],
  ['email' => $secondaryCc,                  'whatsapp' => '+923468205032'],
];

if ($sendDaily || $sendWeekly || $sendMonthly) {
  if ($sendDaily) {
    $overall = filter_tasks($tasks, '', $today, 'day');
    $html = compose_management_grouped_html('All Departments – Daily Summary', $overall, $clients, $today, $TZ);
    $txt  = compose_management_grouped_text('All Departments – Daily Summary', $overall, $clients);
    foreach ($managementContacts as $c) {
      send_email($c['email'], "Daily Tasks Summary (All)", $html, '', true);
      send_whatsapp($c['whatsapp'], $txt);
    }
  }
  if ($sendWeekly) {
    $overall = filter_tasks($tasks, '', $today, 'week');
    $html = compose_management_grouped_html('All Departments – Weekly Summary', $overall, $clients, $today, $TZ);
    $txt  = compose_management_grouped_text('All Departments – Weekly Summary', $overall, $clients);
    foreach ($managementContacts as $c) {
      send_email($c['email'], "Weekly Tasks Summary (All)", $html, '', true);
      send_whatsapp($c['whatsapp'], $txt);
    }
  }
  if ($sendMonthly) {
    $overall = filter_tasks($tasks, '', $today, 'month');
    $html = compose_management_grouped_html('All Departments – Monthly Summary', $overall, $clients, $today, $TZ);
    $txt  = compose_management_grouped_text('All Departments – Monthly Summary', $overall, $clients);
    foreach ($managementContacts as $c) {
      send_email($c['email'], "Monthly Tasks Summary (All)", $html, '', true);
      send_whatsapp($c['whatsapp'], $txt);
    }
  }
}

// Optional: quiet JSON end for manual calls
echo json_encode(['ok' => true]);
