<?php
session_start();
require_once '../config/config.php';
require '../vendor/autoload.php';
require_once '../classes/Employee.php';
require_once '../classes/Client.php';
require_once '../includes/utilities.php';
$config = require '../config/email.php';
$allowedDomains = $config['allowed_domains'] ?? [];

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

header('Content-Type: application/json');

$empObj = new Employee($conn);
$clientObj = new Client($conn);
$response = ['status' => 'error', 'message' => 'Invalid action'];

// Handle both FormData and JSON
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';

if (stripos($contentType, 'application/json') !== false) {
    $data = json_decode(file_get_contents('php://input'), true);
} else {
    $data = $_POST;
}

// To Log add user mails
function logMailStatus($message)
{
    $logFile = __DIR__ . "/bulk_mail_log.txt";
    $timestamp = date("Y-m-d H:i:s");
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}

$action = $data['action'] ?? '';

// Switch based on action
switch ($action) {
    case 'add':
        // Add a new employee
        $role = $data['role'] ?? 'executive';
        $dept_id = $data['dept_id'];
        $subdept_id = $data['subdept_id'] ?? null;
        $emp_id = $data['emp_id'];
        $email = $data['email'];
        // $clients = $data['clients'] ?? []; // should be an array
        // Convert clients string to array
        $clients = isset($data['clients']) ? array_filter(array_map('trim', explode(',', $data['clients']))) : [];


        // Validate email domain
        $domainCheck = isValidCompanyEmail($email, $allowedDomains);
        if ($domainCheck !== true) {
            $response = ['status' => 'error', 'message' => $domainCheck];
            break;
        }

        // Check for duplicate employee ID
        $empIdCheck = $conn->prepare("SELECT emp_id FROM employee WHERE emp_id = ?");
        $empIdCheck->bind_param('i', $emp_id);
        $empIdCheck->execute();
        $empIdCheck->store_result();
        if ($empIdCheck->num_rows > 0) {
            $response = ['status' => 'error', 'message' => 'Employee ID already exists'];
            break;
        }

        // Check for duplicate email
        $emailCheck = $conn->prepare("SELECT emp_id FROM employee WHERE email = ?");
        $emailCheck->bind_param('s', $email);
        $emailCheck->execute();
        $emailCheck->store_result();
        if ($emailCheck->num_rows > 0) {
            $response = ['status' => 'error', 'message' => 'Email already registered'];
            break;
        }

        // Generate random password
        $randStr = generateRandomString(6);
        $firstName = explode(" ", trim($data['name']))[0];
        $randomPassword = $firstName . '@' . $randStr;

        $employeeData = [
            'emp_id' => $emp_id,
            'name' => $data['name'],
            'email' => $email,
            'password' => $randomPassword,
            'role' => $role,
            'dept_id' => $dept_id,
            'subdept_id' => $subdept_id,
            'rm_id' => null,
            'doj' => date('Y-m-d')
        ];

        if ($role === 'executive' || $role === 'rm') {
            $employeeData['rm_id'] = $data['rm_id'] ?? null;
        } elseif ($role === 'hod') {
            $hodCheck = $conn->prepare("SELECT emp_id FROM employee WHERE role = 'hod' AND dept_id = ?");
            $hodCheck->bind_param('i', $dept_id);
            $hodCheck->execute();
            $hodCheck->store_result();

            if ($hodCheck->num_rows > 0) {
                $response = ['status' => 'error', 'message' => 'An HOD already exists for this department'];
                break;
            }

            $employeeData['rm_id'] = 1; // admin
        }

        $roleName = ucfirst($role);

        if ($empObj->addEmployee($employeeData)) {

            // Assign clients if any
            if (!empty($clients)) {
                $clientResult = $clientObj->addClientsToEmployeeId($clients, $emp_id);
                if ($clientResult['status'] !== 'success') {
                    $response = ['status' => 'warning', 'message' => "$roleName added but failed to assign some clients."];
                    $_SESSION['success'] = false;
                    $_SESSION['message'] = "$roleName added but failed to assign some clients.";
                    break;
                }
            }

            // If HOD, update dept head
            if (strtolower($role) === 'hod') {
                $updateDept = $conn->prepare("UPDATE department SET dept_head = ? WHERE dept_id = ?");
                $updateDept->bind_param('ii', $emp_id, $dept_id);
                $updateDept->execute();
            }

            // $response = ['status' => 'success', 'message' => "$role added successfully !"];
            // $_SESSION['success'] = true;
            // $_SESSION['message'] = "$role added successfully !";

            $name = $employeeData['name'];
            $email = $employeeData['email'];
            $password = $employeeData['password'];
            // Send email using PHPMailer
            $mail = new PHPMailer(true);
            try {
                // Server settings
                $mail->isSMTP();
                $mail->Host = 'smtp.gmail.com'; // Your SMTP server
                $mail->SMTPAuth = true;
                $mail->Username = 'timesheet.owner@wildnettechnologies.com';
                $mail->Password = 'nhik tmto wspf iskz';
                $mail->SMTPSecure = 'tls';                    // Encryption (tls or ssl)
                $mail->Port = 587;                      // TCP port

                // Recipients
                $mail->setFrom('timesheet.owner@wildnettechnologies.com', 'WildNet Timesheet Portal');
                $domainCheck = isValidCompanyEmail($email, $allowedDomains);
                if ($domainCheck !== true) {
                    throw new Exception("Email blocked from sending: " . $domainCheck);
                }
                $mail->addAddress($email, $name);

                // Content
                $mail->isHTML(true);
                $mail->Subject = 'Account Details for Wildnet Timesheet Portal';
                $loginUrl = "https://timesheet.wildnettechnologies.com";

                $mail->Body = "
                    <p><strong>Dear $name,</strong></p>
                    <p>We are pleased to inform you that your account has been successfully created in the Wildnet Timesheet Portal. Please find your login details below.</p>
                    <p>Your Login Credentials:</p>
                    <ul>
                        <li>Email Id: $email</li>
                        <li>Password: $password</li>
                        <li>Timesheet Link: <a href='$loginUrl'>$loginUrl</a></li>
                    </ul>
                                            
                    <p><strong>Important Instructions:</strong></p>
                    <ul>
                        <li>Use the above credentials to log in for the first time.</li>
                        <li>Change your password after log in to keep your account secure.</li>
                        <li>Keep your login credentials confidential and do not share them with anyone.</li>
                    </ul>
                    <p>If you encounter any issues during login or need assistance, please contact our support team at timesheet.owner@wildnettechnologies.com.
                    We are excited to have you onboard and look forward to your contribution to Wildnet.</p>
                    <b>Best Regards,</b><br>
                    <b>HR Team</b> <br>
                    <b>Wildnet Technologies Ltd.</b>
                ";

                // $mail->Body = "
                //     <h3>Dear $name,</h3>
                //     <p>Your account has been successfully created.</p>
                //     <p><strong>Login Details:</strong></p>
                //     <ul>
                //         <li>Email: $email</li>
                //         <li>Password: $password</li>
                //     </ul>
                //     <p>You can log in here: <a href='$loginUrl'>$loginUrl</a></p>
                //     <p>Please make sure to change your password after your first login.</p>
                //     <br>
                //     <p>Regards,<br>Admin Team</p>
                // ";

                $mail->AltBody = "Dear $name,\n\nYour account has been successfully created.\n\nLogin Details:\nEmail: $email\nPassword: $password\n\nLogin here: $loginUrl\n\nPlease change your password after your first login.\n\nRegards,\nHR Team Wildnet";
                if ($mail->send()) {
                    $msg = "SUCCESS: Mail sent to $name <$email>";
                    logMailStatus($msg);
                    $response = ['status' => 'success', 'message' => "$role added successfully, Mail sent !", 'client_data' => $clients];
                    $_SESSION['success'] = true;
                    $_SESSION['message'] = "$role added successfully, Mail sent !";
                    // $_SESSION['client_data'] = $clients;
                } else {
                    $msg = "FAIL: Could not send mail to $name <$email>";
                    logMailStatus($msg);
                    $response = ['status' => 'error', 'message' => "$role added, Mail send failed !"];
                    $_SESSION['success'] = false;
                    $_SESSION['message'] = "$role added, Mail send failed !";
                }
            } catch (Exception $e) {
                $msg = "ERROR: $name <$email> - " . $mail->ErrorInfo;
                logMailStatus($msg);
                $response = ['status' => 'error', 'message' => $e->getMessage()];
                $_SESSION['success'] = false;
                $_SESSION['message'] = $e->getMessage();
            }
            $response = ['status' => 'success', 'message' => "$role added successfully"];
        } else {
            $response = ['status' => 'error', 'message' => "Failed to add $role"];
            $_SESSION['success'] = false;
            $_SESSION['message'] = "Failed to add $role";
        }
        break;

    // Edit an employee
    case 'edit':
        $id = $data['id'];
        $role = $data['role'] ?? 'executive';
        $dept_id = $data['dept_id'] ?? null;
        $subdept_id = $data['subdept_id'] ?? null;

        $employeeData = [];

        $possibleFields = ['name', 'email', 'password', 'role', 'dept_id', 'subdept_id'];

        foreach ($possibleFields as $field) {
            if (isset($data[$field]) && $data[$field] !== '') {
                $employeeData[$field] = $data[$field];
            }
        }

        // Force subdept_id to 0 if not sent or empty
        if (!isset($employeeData['subdept_id']) || $employeeData['subdept_id'] === '') {
            $employeeData['subdept_id'] = 0;
        }

        // Check for duplicate email (excluding current employee)
        if (isset($employeeData['email'])) {

            // Validate email domains
            $domainCheck = isValidCompanyEmail($employeeData['email'], $allowedDomains); // Add all allowed domains here
            if ($domainCheck !== true) {
                $response = ['status' => 'error', 'message' => $domainCheck];
                break;
            }

            $emailCheck = $conn->prepare("SELECT emp_id FROM employee WHERE email = ? AND emp_id != ?");
            $emailCheck->bind_param('si', $employeeData['email'], $id);
            $emailCheck->execute();
            $emailCheck->store_result();

            if ($emailCheck->num_rows > 0) {
                $response = ['status' => 'error', 'message' => 'Email is already registered to another employee'];
                break;
            }
        }

        // Role-based RM assignment logic
        if ($role === 'executive' || $role === 'rm') {
            $employeeData['rm_id'] = $data['rm_id'] ?? null;
        }
        // elseif ($role === 'rm') {
        //     // Assign HOD of dept as RM
        //     $hodQuery = $conn->prepare("SELECT emp_id FROM employee WHERE role = 'hod' AND dept_id = ? ORDER BY emp_id DESC");
        //     $hodQuery->bind_param('i', $dept_id);
        //     $hodQuery->execute();
        //     $hodResult = $hodQuery->get_result();
        //     if ($hodRow = $hodResult->fetch_assoc()) {
        //         $employeeData['rm_id'] = $hodRow['emp_id'];
        //     } else {
        //         $response = ['status' => 'error', 'message' => 'No HOD found for selected department. Please add a HOD first.'];
        //         break;
        //     }
        // }
        elseif ($role === 'hod') {
            // Check if another HOD exists for the department (excluding current user)
            $hodCheck = $conn->prepare("SELECT emp_id FROM employee WHERE role = 'hod' AND dept_id = ? AND emp_id != ?");
            $hodCheck->bind_param('ii', $dept_id, $id);
            $hodCheck->execute();
            $hodCheck->store_result();

            if ($hodCheck->num_rows > 0) {
                $response = ['status' => 'error', 'message' => 'Another HOD already exists for this department'];
                break;
            }

            $employeeData['rm_id'] = 1; // Admin is RM for HOD
        }

        $clients = isset($data['clients']) ? array_filter(array_map('trim', explode(',', $data['clients']))) : [];

        $role = ucfirst($role);
        if ($empObj->updateEmployee($id, $employeeData)) {


            $clientResult = $clientObj->addClientsToEmployeeId($clients, $id);
            if ($clientResult['status'] !== 'success') {
                $response = [
                    'status' => 'warning',
                    'message' => "$role updated, but client assignment failed."
                ];
                $_SESSION['success'] = false;
                $_SESSION['message'] = "$role updated, but client assignment failed.";
                break;
            }

            // Assign clients if any
            // if (!empty($clients)) {
            //         $response = ['status' => 'warning', 'message' => "$roleName added but failed to assign some clients."];
            //     $clientResult = $clientObj->addClientsToEmployeeId($clients, $id);
            //     if ($clientResult['status'] !== 'success') {
            //         $_SESSION['success'] = false;
            //         $_SESSION['message'] = "$roleName added but failed to assign some clients.";
            //         break;
            //     }
            // }

            // If updated employee is HOD, update dept_head in department table
            if (strtolower($role) === 'hod') {
                $updateDept = $conn->prepare("UPDATE department SET dept_head = ? WHERE dept_id = ?");
                $updateDept->bind_param('ii', $id, $dept_id);
                $updateDept->execute();
            }

            $response = ['status' => 'success', 'message' => "$role updated successfully"];
            $_SESSION['success'] = true;
            $_SESSION['message'] = "$role updated successfully";
        } else {
            $_SESSION['success'] = false;
            $_SESSION['message'] = "Failed to update $role";
            $response = ['status' => 'error', 'message' => "Failed to update $role"];
        }
        break;

    // Activate/Deactivate user
    case 'toggle_status':
        $emp_id = $data['employee_id'] ?? null;
        $status = $data['status'] ?? null;

        if ($emp_id === null || $status === null) {
            $response = ['status' => 'error', 'message' => 'Invalid input'];
            break;
        }

        $stmt = $conn->prepare("UPDATE employee SET status = ? WHERE emp_id = ?");
        $stmt->bind_param("ii", $status, $emp_id);

        if ($stmt->execute()) {
            $response = ['status' => 'success'];
        } else {
            $response = ['status' => 'error', 'message' => 'Database error'];
        }
        break;

    // Delete an employee
    case 'delete':
        $id = $data['id'];
        if ($empObj->deleteEmployee($id)) {
            $response = ['status' => 'success', 'message' => "Employee with id: $id deleted"];
        } else {
            $response = ['status' => 'error', 'message' => "Failed to delete employee with id: $id"];
        }
        break;

    // Get one employee
    case 'get':
        $id = $data['id'];
        $emp = $empObj->getEmployeeById($id);
        if ($emp) {
            $assignedClients = $clientObj->getClientsByEmployeeId($id) ?? null;
            $response = ['status' => 'success', 'emp' => $emp, 'assignedClients' => $assignedClients];
        } else {
            $response = ['status' => 'error', 'message' => 'Employee not found'];
        }
        break;

    // List all employees
    case 'list':
        $employees = $empObj->getAllEmployees();
        $employeeHTML = '';

        ob_start(); // Start output buffering

        if (!empty($executives)) {
            $i = 1;
            foreach ($executives as $executive) {
                ?>
                <tr>
                    <td><?= $i . "." ?></td>
                    <td><?= $executive['emp_id'] ?></td>
                    <td><?= $executive['name'] ?></td>
                    <td><?= $executive['email'] ?></td>
                    <td><?= $executive['dept_name'] ?></td>
                    <td><?= $executive['rm_name'] . " (" . $executive['rm_id'] . ")" ?></td>
                    <td class="actions">
                        <i class="fa-solid fa-eye open-modal-btn" data-modal="executive" data-mode="view"
                            data-id="<?= $executive['emp_id'] ?>"></i>
                        <i class="fa-solid fa-pencil open-modal-btn" data-modal="executive" data-mode="edit"
                            data-id="<?= $executive['emp_id'] ?>"></i>
                        <i class="fa-solid fa-trash-can delete-btn-emp" data-mode="delete" data-id="<?= $executive['emp_id'] ?>"></i>
                        <label class="switch">
                            <input type="checkbox" class="toggle-status" data-id="<?= $executive['emp_id'] ?>" <?= $executive['status'] ? 'checked' : '' ?>>
                            <span class="slider round"></span>
                        </label>
                    </td>
                </tr>
                <?php
                $i++;
            }
            echo '<tr class="no-entries-row" style="background-color: #e0f5ff;display:none;">
            <td colspan="7" style="text-align: center;">
                <h3>No Entries</h3>
            </td>
        </tr>';
        } else {
            ?>
            <tr style="background-color: #ffe0e0ff;">
                <td colspan="7" style="text-align: center;">
                    <h3>No Entries</h3>
                </td>
            </tr>
            <?php
        }

        $html = ob_get_clean(); // Get buffered content

        echo json_encode([
            "success" => true,
            "data" => $html
        ]);
        exit;

    // // Get RMs by department
    // case 'rmsByDept':
    //     $dept_id = $data['dept_id'];
    //     $rms = $empObj->getRMsByDepartment($dept_id);
    //     $response = ['status' => 'success', 'rms' => array_values($rms)];
    //     break;

    // // Get RMs by Subdepartment
    // case 'rmsBySubdept':
    //     $subdept_id = $data['id'];
    //     $rms = $empObj->getRMsBySubDepartment($subdept_id);
    //     $response = ['status' => 'success', 'rms' => array_values($rms)];
    //     break;

    // Unified RM fetcher based on dept or subdept
    case 'get-rms':
        $dept_id = $data['dept_id'] ?? null;
        $subdept_id = $data['subdept_id'] ?? null;

        if ($subdept_id) {
            $rms = $empObj->getRMsBySubDepartment($subdept_id);
        } else {
            $rms = $empObj->getRMsByDepartment($dept_id);
        }

        if ($rms) {
            $response = ['status' => 'success', 'rms' => array_values($rms)];

        } else {
            $response = ['status' => 'error', 'message' => 'No Managers Found'];
        }
        // $response = ['status' => 'success', 'rms' => array_values($rms)];
        break;
}

echo json_encode($response);


