<?php
declare(strict_types=1);

/*
  inc/hr_leave_notifications.php
  - إشعار الإدارة عند إنشاء طلب إجازة
  - إشعار الموظف عند تغيير حالة الطلب
  - إظهار سبب الرفض في بريد الموظف عند رفض الإجازة
*/

require_once __DIR__ . '/mailer.php';
require_once __DIR__ . '/db.php';

if (!function_exists('hr_h')) {
    function hr_h($v): string
    {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('hr_has_col')) {
    function hr_has_col(PDO $pdo, string $table, string $col): bool
    {
        static $cache = [];
        $key = spl_object_id($pdo) . ':' . $table;

        if (!isset($cache[$key])) {
            $st = $pdo->query("SHOW COLUMNS FROM `$table`");
            $cache[$key] = $st->fetchAll(PDO::FETCH_COLUMN, 0);
        }

        return in_array($col, $cache[$key], true);
    }
}

if (!function_exists('hr_table_exists')) {
    function hr_table_exists(PDO $pdo, string $table): bool
    {
        try {
            $pdo->query("SELECT 1 FROM `$table` LIMIT 1");
            return true;
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('hr_employee_name_expr')) {
    function hr_employee_name_expr(PDO $pdo): string
    {
        if (!hr_table_exists($pdo, 'employees')) {
            return "'موظف'";
        }

        $st = $pdo->query("SHOW COLUMNS FROM `employees`");
        $cols = $st->fetchAll(PDO::FETCH_COLUMN, 0);

        foreach (['full_name', 'display_name', 'name', 'employee_name', 'emp_name', 'first_name'] as $c) {
            if (in_array($c, $cols, true)) {
                return "COALESCE(NULLIF(e.`{$c}`, ''), CONCAT('EMP#', e.id))";
            }
        }

        return "CONCAT('EMP#', e.id)";
    }
}

if (!function_exists('hr_branch_name')) {
    function hr_branch_name(int $branchId): string
    {
        return match ($branchId) {
            2       => 'دبي',
            3       => 'الشارقة',
            4       => 'العين',
            default => 'أبوظبي',
        };
    }
}

if (!function_exists('hr_branch_email')) {
    function hr_branch_email(int $branchId): string
    {
        return match ($branchId) {
            2       => 'contact.dxb@hamdanlegalgroup.ae',
            default => 'contact@hamdanlegalgroup.ae',
        };
    }
}

if (!function_exists('hr_email_rtl_wrap')) {
    function hr_email_rtl_wrap(string $innerHtml, string $bg = '#f4f7f9'): string
    {
        return '
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<body style="margin:0;padding:0;background:' . $bg . ';direction:rtl;text-align:right;">
<div style="direction:rtl;text-align:right;">' . $innerHtml . '</div>
</body>
</html>';
    }
}

if (!function_exists('hr_get_pdo')) {
    function hr_get_pdo(): ?PDO
    {
        $pdo = function_exists('dbx') ? dbx() : (function_exists('db') ? db() : null);

        if (!$pdo instanceof PDO) {
            return null;
        }

        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

        return $pdo;
    }
}

if (!function_exists('send_leave_request_email')) {
    function send_leave_request_email(int $leaveRequestId): array
    {
        $pdo = hr_get_pdo();
        if (!$pdo) return ['ok' => 0, 'err' => 'pdo_not_ready'];

        if (!hr_table_exists($pdo, 'leave_requests')) {
            return ['ok' => 0, 'err' => 'leave_requests_table_missing'];
        }

        $empNameExpr = hr_employee_name_expr($pdo);

        $st = $pdo->prepare("
            SELECT
                r.id,
                r.leave_type,
                r.date_from,
                r.date_to,
                COALESCE(r.reason,'') AS reason,
                COALESCE(r.created_at, NOW()) AS created_at,
                COALESCE(r.branch_id, 0) AS branch_id,
                {$empNameExpr} AS employee_name
            FROM leave_requests r
            JOIN employees e ON e.id = r.employee_id
            WHERE r.id = ?
            LIMIT 1
        ");
        $st->execute([$leaveRequestId]);
        $row = $st->fetch();

        if (!$row) return ['ok' => 0, 'err' => 'leave_not_found'];

        $branchId   = (int)($row['branch_id'] ?? 0);
        $branchName = hr_branch_name($branchId);
        $to         = hr_branch_email($branchId);

        $typeMap = [
            'ANNUAL'    => 'سنوية',
            'SICK'      => 'مرضية',
            'EMERGENCY' => 'طارئة',
            'OTHER'     => 'أخرى',
        ];

        $typeAr = $typeMap[(string)($row['leave_type'] ?? '')] ?? (string)($row['leave_type'] ?? '');
        $subject = "طلب إجازة جديد - {$branchName} - " . (string)($row['employee_name'] ?? 'موظف');
        $viewUrl = 'https://hamdanlegalgroup.ae/HLG-Justice-Hub/hr_leaves.php?view=' . (int)$row['id'];

        $inner = '
<table width="100%" cellpadding="0" cellspacing="0" style="padding:24px 12px;direction:rtl;text-align:right;">
<tr><td align="center">
<table width="680" cellpadding="0" cellspacing="0" dir="rtl" style="max-width:680px;background:#fff;border-radius:16px;overflow:hidden;box-shadow:0 6px 24px rgba(0,0,0,.08);">
<tr>
<td style="background:linear-gradient(135deg,#00424f,#006a7a);padding:18px 22px;color:#fff;font-family:Tahoma,Arial;">
<div style="font-size:14px;opacity:.95;">Hamdan Legal Group - HLG HR</div>
<div style="font-size:20px;margin-top:6px;">طلب إجازة جديد</div>
</td>
</tr>
<tr>
<td style="padding:16px 22px;font-family:Tahoma,Arial;color:#0b1f2a;">
<table width="100%" cellpadding="0" cellspacing="0" dir="rtl" style="border:1px solid #e6eef2;border-radius:12px;overflow:hidden;">
<tr><td style="padding:12px 14px;background:#f8fbfc;color:#4a6472;width:32%;">الفرع</td><td style="padding:12px 14px;">' . hr_h($branchName) . '</td></tr>
<tr><td style="padding:12px 14px;background:#f8fbfc;color:#4a6472;">الموظف</td><td style="padding:12px 14px;">' . hr_h($row['employee_name'] ?? 'موظف') . '</td></tr>
<tr><td style="padding:12px 14px;background:#f8fbfc;color:#4a6472;">نوع الإجازة</td><td style="padding:12px 14px;">' . hr_h($typeAr) . '</td></tr>
<tr><td style="padding:12px 14px;background:#f8fbfc;color:#4a6472;">من</td><td style="padding:12px 14px;">' . hr_h($row['date_from'] ?? '') . '</td></tr>
<tr><td style="padding:12px 14px;background:#f8fbfc;color:#4a6472;">إلى</td><td style="padding:12px 14px;">' . hr_h($row['date_to'] ?? '') . '</td></tr>
<tr><td style="padding:12px 14px;background:#f8fbfc;color:#4a6472;">السبب</td><td style="padding:12px 14px;">' . hr_h(trim((string)($row['reason'] ?? '')) ?: '—') . '</td></tr>
<tr><td style="padding:12px 14px;background:#f8fbfc;color:#4a6472;">وقت الإرسال</td><td style="padding:12px 14px;">' . hr_h($row['created_at'] ?? '') . '</td></tr>
<tr><td style="padding:12px 14px;background:#f8fbfc;color:#4a6472;">رقم الطلب</td><td style="padding:12px 14px;">#' . (int)$row['id'] . '</td></tr>
</table>

<div style="margin-top:14px;">
<a href="' . hr_h($viewUrl) . '" style="display:inline-block;background:#006a7a;color:#fff;text-decoration:none;padding:12px 16px;border-radius:12px;font-size:14px;">عرض الطلب</a>
</div>

<div style="margin-top:14px;color:#6b7f8a;font-size:12.5px;line-height:1.7;">هذه رسالة آلية من نظام الموارد البشرية.</div>
</td>
</tr>
<tr>
<td style="background:#0b2633;padding:12px 22px;color:#cfe2ea;font-family:Tahoma,Arial;font-size:12px;">© ' . date('Y') . ' Hamdan Legal Group. جميع الحقوق محفوظة.</td>
</tr>
</table>
</td></tr>
</table>';

        $html = hr_email_rtl_wrap($inner);

        $res = send_mail($to, $subject, $html, MAIL_FROM, MAIL_FROM_NAME, true);
        $res['to'] = $to;
        $res['kind'] = 'admin_new_request';
        $res['leave_id'] = (int)$row['id'];
        $res['branch_id'] = $branchId;
        $res['branch_name'] = $branchName;

        return $res;
    }
}

if (!function_exists('send_leave_status_to_employee')) {
    function send_leave_status_to_employee(PDO $pdo, int $leaveRequestId): array
    {
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

        if (!hr_table_exists($pdo, 'leave_requests')) return ['ok' => 0, 'err' => 'leave_requests_table_missing'];
        if (!hr_table_exists($pdo, 'employees')) return ['ok' => 0, 'err' => 'employees_table_missing'];
        if (!hr_table_exists($pdo, 'users')) return ['ok' => 0, 'err' => 'users_table_missing'];
        if (!hr_has_col($pdo, 'employees', 'user_id')) return ['ok' => 0, 'err' => 'employees_user_id_missing'];

        $empNameExpr = hr_employee_name_expr($pdo);
        $hasBranchId = hr_has_col($pdo, 'leave_requests', 'branch_id');
        $hasRejectionNote = hr_has_col($pdo, 'leave_requests', 'rejection_note');

        $rejectionSelect = $hasRejectionNote
            ? "COALESCE(r.rejection_note,'') AS rejection_note,"
            : "'' AS rejection_note,";

        $st = $pdo->prepare("
            SELECT
                r.id,
                r.status,
                r.leave_type,
                r.date_from,
                r.date_to,
                COALESCE(r.reason,'') AS reason,
                {$rejectionSelect}
                COALESCE(r.decided_at, NOW()) AS decided_at,
                " . ($hasBranchId ? "COALESCE(r.branch_id,0) AS branch_id," : "0 AS branch_id,") . "
                e.id AS employee_id,
                {$empNameExpr} AS employee_name,
                COALESCE(NULLIF(u.email,''),'') AS user_email
            FROM leave_requests r
            JOIN employees e ON e.id = r.employee_id
            JOIN users u ON u.id = e.user_id
            WHERE r.id = ?
            LIMIT 1
        ");
        $st->execute([$leaveRequestId]);
        $row = $st->fetch();

        if (!$row) return ['ok' => 0, 'err' => 'leave_not_found'];

        $to = trim((string)$row['user_email']);
        if ($to === '' || !filter_var($to, FILTER_VALIDATE_EMAIL)) {
            return ['ok' => 0, 'err' => 'user_email_missing'];
        }

        $status = strtoupper((string)$row['status']);

        $statusAr = match ($status) {
            'APPROVED'  => 'تم اعتماد',
            'REJECTED'  => 'تم رفض',
            'CANCELLED' => 'تم الإلغاء',
            default     => $status,
        };

        $typeMap = [
            'ANNUAL'    => 'سنوية',
            'SICK'      => 'مرضية',
            'EMERGENCY' => 'طارئة',
            'OTHER'     => 'أخرى',
        ];

        $typeAr = $typeMap[(string)($row['leave_type'] ?? '')] ?? (string)($row['leave_type'] ?? '');

        $leaveId       = (int)$row['id'];
        $branchId      = (int)($row['branch_id'] ?? 0);
        $branchName    = hr_branch_name($branchId);
        $viewUrl       = 'https://hamdanlegalgroup.ae/HLG-Justice-Hub/hr_leaves.php?view=' . $leaveId;
        $reasonTxt     = trim((string)$row['reason']) ?: '—';
        $rejectionNote = trim((string)($row['rejection_note'] ?? ''));

        $badgeBg = ($status === 'APPROVED') ? '#e8fff0' : (($status === 'REJECTED') ? '#fff0f0' : '#f0f4ff');
        $badgeBd = ($status === 'APPROVED') ? '#33c26b' : (($status === 'REJECTED') ? '#ff6b6b' : '#6b8cff');
        $badgeTx = ($status === 'APPROVED') ? '#1a7f3b' : (($status === 'REJECTED') ? '#a61b1b' : '#2740b5');

        $rejectionHtml = '';

        if ($status === 'REJECTED') {
            $rejectionHtml = '
<tr>
<td style="padding:12px 14px;background:#fff5f5;color:#a61b1b;font-family:Tahoma,Arial;">سبب الرفض</td>
<td style="padding:12px 14px;background:#fffafa;color:#7a1f1f;font-family:Tahoma,Arial;line-height:1.8;">' . hr_h($rejectionNote !== '' ? $rejectionNote : 'لم يتم تسجيل سبب الرفض') . '</td>
</tr>';
        }

        $subject = "تحديث طلب الإجازة رقم #{$leaveId} - {$statusAr} - {$branchName}";

        $inner = '
<table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f7f9;padding:24px 12px;direction:rtl;text-align:right;">
<tr><td align="center">
<table width="680" cellpadding="0" cellspacing="0" dir="rtl" style="max-width:680px;background:#ffffff;border-radius:16px;overflow:hidden;box-shadow:0 6px 24px rgba(0,0,0,.08);">
<tr>
<td style="background:linear-gradient(135deg,#00424f,#006a7a);padding:18px 22px;">
<div style="color:#ffffff;font-family:Tahoma,Arial;font-size:14px;opacity:.95;">Hamdan Legal Group - HLG HR</div>
<div style="color:#ffffff;font-family:Tahoma,Arial;font-size:20px;margin-top:6px;">تحديث حالة طلب الإجازة</div>
</td>
</tr>

<tr>
<td style="padding:18px 22px 6px 22px;font-family:Tahoma,Arial;color:#0b1f2a;">
<div style="font-size:14px;color:#49616f;">مرحبًا ' . hr_h($row['employee_name'] ?? 'الموظف') . '</div>
<div style="margin-top:10px;">
<span style="display:inline-block;padding:8px 12px;border-radius:999px;background:' . $badgeBg . ';border:1px solid ' . $badgeBd . ';color:' . $badgeTx . ';font-size:13px;">الحالة الحالية: ' . hr_h($statusAr) . '</span>
<span style="display:inline-block;margin-right:10px;color:#6b7f8a;font-size:13px;">رقم الطلب: #' . $leaveId . '</span>
<span style="display:inline-block;margin-right:10px;color:#6b7f8a;font-size:13px;">الفرع: ' . hr_h($branchName) . '</span>
</div>
</td>
</tr>

<tr>
<td style="padding:14px 22px 10px 22px;">
<table width="100%" cellpadding="0" cellspacing="0" dir="rtl" style="border:1px solid #e6eef2;border-radius:12px;overflow:hidden;">
<tr><td style="padding:12px 14px;background:#f8fbfc;color:#4a6472;font-family:Tahoma,Arial;width:32%;">نوع الإجازة</td><td style="padding:12px 14px;background:#ffffff;color:#0b1f2a;font-family:Tahoma,Arial;">' . hr_h($typeAr) . '</td></tr>
<tr><td style="padding:12px 14px;background:#f8fbfc;color:#4a6472;font-family:Tahoma,Arial;">من</td><td style="padding:12px 14px;background:#ffffff;color:#0b1f2a;font-family:Tahoma,Arial;">' . hr_h($row['date_from'] ?? '') . '</td></tr>
<tr><td style="padding:12px 14px;background:#f8fbfc;color:#4a6472;font-family:Tahoma,Arial;">إلى</td><td style="padding:12px 14px;background:#ffffff;color:#0b1f2a;font-family:Tahoma,Arial;">' . hr_h($row['date_to'] ?? '') . '</td></tr>
<tr><td style="padding:12px 14px;background:#f8fbfc;color:#4a6472;font-family:Tahoma,Arial;">سبب الطلب</td><td style="padding:12px 14px;background:#ffffff;color:#0b1f2a;font-family:Tahoma,Arial;">' . hr_h($reasonTxt) . '</td></tr>
' . $rejectionHtml . '
<tr><td style="padding:12px 14px;background:#f8fbfc;color:#4a6472;font-family:Tahoma,Arial;">وقت القرار</td><td style="padding:12px 14px;background:#ffffff;color:#0b1f2a;font-family:Tahoma,Arial;">' . hr_h($row['decided_at'] ?? '') . '</td></tr>
</table>
</td>
</tr>

<tr>
<td style="padding:8px 22px 22px 22px;font-family:Tahoma,Arial;">
<a href="' . hr_h($viewUrl) . '" style="display:inline-block;background:#006a7a;color:#ffffff;text-decoration:none;padding:12px 16px;border-radius:12px;font-size:14px;">عرض الطلب</a>
<div style="margin-top:16px;color:#6b7f8a;font-size:12.5px;line-height:1.7;">هذه رسالة آلية من نظام الموارد البشرية.</div>
</td>
</tr>

<tr>
<td style="background:#0b2633;padding:12px 22px;color:#cfe2ea;font-family:Tahoma,Arial;font-size:12px;">© ' . date('Y') . ' Hamdan Legal Group. جميع الحقوق محفوظة.</td>
</tr>
</table>
</td></tr>
</table>';

        $html = hr_email_rtl_wrap($inner);

        $res = send_mail($to, $subject, $html, MAIL_FROM, MAIL_FROM_NAME, true);
        $res['to'] = $to;
        $res['kind'] = 'employee_status';
        $res['leave_id'] = $leaveId;
        $res['branch_id'] = $branchId;
        $res['branch_name'] = $branchName;

        return $res;
    }
}

if (!function_exists('send_leave_to_admin')) {
    function send_leave_to_admin(int $leaveRequestId): array
    {
        return send_leave_request_email($leaveRequestId);
    }
}