<?php
// controllers/AssignEngineerController.php

/**
 * AssignEngineerController for Rehlko Customer Care application.
 * Manages CRUD operations for engineer assignments (engineer_id, start_date, end_date).
 * Access for create, update, delete is restricted to 'superadmin', 'supervisor', 'admin' roles.
 * Read access is role-based and handled by the model.
 */
class AssignEngineerController {
    private $conn;
    private $assignEngineerModel;
    private $notificationModel;
    private $mailer;
    private $userModel;

    /**
     * Constructor for AssignEngineerController.
     *
     * @param mysqli $db The database connection object.
     */
    public function __construct($db) {
        $this->conn = $db;
        // The AssignEngineer model needs to be defined in models/AssignEngineer.php
        // and should have properties like $engineer_id, $start_date, $end_date
        // and CRUD methods (create, readAll, readOne, update, delete, etc.)
        $this->assignEngineerModel = new AssignEngineer($db); 
        $this->notificationModel = new Notification($db);
        $this->mailer = new Mailer();
         $this->userModel = new User($db);
    }

    //------------------------------------------------------------------------------------------------------------------

    /**
     * Assigns an engineer with start and end dates.
     * Only 'superadmin', 'supervisor', 'admin' roles are authorized.
     */
    public function create() {
        // Check authorization
        $currentUserRole = getCurrentUserRole();
        if (!in_array($currentUserRole, ['superadmin', 'supervisor', 'admin'])) {
            sendJsonResponse(['message' => 'Unauthorized. Only superadmin, supervisor, or admin can assign engineers.'], 403);
            return;
        }

        $data = json_decode(file_get_contents("php://input"));

        // Validate required fields
        if (empty($data->engineer_id) || empty($data->start_date) || empty($data->end_date)) {
            sendJsonResponse(['message' => 'Missing required fields: engineer_id, start_date, or end_date.'], 400);
            return;
        }

        // Set engineer assignment properties
        $this->assignEngineerModel->engineer_id = $data->engineer_id;
        $this->assignEngineerModel->start_date = $data->start_date;
        $this->assignEngineerModel->end_date = $data->end_date;

        if ($this->assignEngineerModel->create()) {
             $this->sendNewAssignNotifications($this->assignEngineerModel->engineer_id);
            sendJsonResponse(['message' => 'Engineer assigned successfully.', 'assignmentId' => $this->assignEngineerModel->id], 201);
        } else {
            sendJsonResponse(['message' => 'Failed to assign engineer.'], 500);
        }
    }

    //------------------------------------------------------------------------------------------------------------------

    /**
     * Reads all engineer assignments.
     * Access is restricted based on user role and inclusion in the assignment, handled by the model.
     */
    public function readAll() {
        $currentUserRole = getCurrentUserRole();
        if (!$currentUserRole) {
            sendJsonResponse(['message' => 'Authentication required.'], 401);
            return;
        }

        $result = $this->assignEngineerModel->readAll(); // Model handles authorization

        if ($result) {
            $assignments_arr = [];
            while ($row = $result->fetch_assoc()) {
                $assignments_arr[] = $row;
            }
            sendJsonResponse(['data'=>$assignments_arr]);
        } else {
            sendJsonResponse(['message' => 'Failed to retrieve engineer assignments or unauthorized.'], 403);
        }
    }

    //------------------------------------------------------------------------------------------------------------------

    /**
     * Reads a single engineer assignment by ID.
     * Access is restricted based on user role and inclusion in the assignment, handled by the model.
     *
     * @param int $id The ID of the engineer assignment to retrieve.
     */
    public function read($id) {
        $currentUserRole = getCurrentUserRole();
        if (!$currentUserRole) {
            sendJsonResponse(['message' => 'Authentication required.'], 401);
            return;
        }

        $this->assignEngineerModel->id = $id;
        $assignment = $this->assignEngineerModel->readOne(); // Model handles authorization

        if ($assignment) {
            sendJsonResponse($assignment);
        } else {
            sendJsonResponse(['message' => 'Engineer assignment not found or unauthorized.'], 404);
        }
    }

    //------------------------------------------------------------------------------------------------------------------

    /**
     * Updates an existing engineer assignment.
     * Only 'superadmin', 'supervisor', 'admin' roles are authorized.
     *
     * @param int $id The ID of the engineer assignment to update.
     */
    public function update($id) {
        // Check authorization
        $currentUserRole = getCurrentUserRole();
        if (!in_array($currentUserRole, ['superadmin', 'supervisor', 'admin'])) {
            sendJsonResponse(['message' => 'Unauthorized. Only superadmin, supervisor, or admin can update engineer assignments.'], 403);
            return;
        }

        $data = json_decode(file_get_contents("php://input"));

        // Check if assignment exists
        $this->assignEngineerModel->id = $id;
        if (!$this->assignEngineerModel->readOne()) {
            sendJsonResponse(['message' => 'Engineer assignment not found.'], 404);
            return;
        }

        // Set properties for update (only update if provided in the payload)
        $this->assignEngineerModel->engineer_id = $data->engineer_id ?? $this->assignEngineerModel->engineer_id;
        $this->assignEngineerModel->start_date = $data->start_date ?? $this->assignEngineerModel->start_date;
        $this->assignEngineerModel->end_date = $data->end_date ?? $this->assignEngineerModel->end_date;
        $this->assignEngineerModel->id = $id;

        if ($this->assignEngineerModel->update()) {
            sendJsonResponse(['message' => 'Engineer assignment updated successfully.'], 200);
        } else {
            sendJsonResponse(['message' => 'Failed to update engineer assignment.'], 500);
        }
    }

    //------------------------------------------------------------------------------------------------------------------

    /**
     * Deletes an engineer assignment.
     * Only 'superadmin', 'supervisor', 'admin' roles are authorized.
     *
     * @param int $id The ID of the engineer assignment to delete.
     */
    public function delete($id) {
        // Check authorization
        $currentUserRole = getCurrentUserRole();
        if (!in_array($currentUserRole, ['superadmin', 'supervisor', 'admin'])) {
            sendJsonResponse(['message' => 'Unauthorized. Only superadmin, supervisor, or admin can delete engineer assignments.'], 403);
            return;
        }

        $this->assignEngineerModel->id = $id;

        if ($this->assignEngineerModel->delete()) {
            sendJsonResponse(['message' => 'Engineer assignment deleted successfully.'], 200);
        } else {
            sendJsonResponse(['message' => 'Failed to delete engineer assignment or assignment not found.'], 500);
        }
    }
    
    private function sendNewAssignNotifications(int $receiver_id): void
    {
        $engineer = $this->userModel->readById($receiver_id);
        if ($engineer) {
            $this->notificationModel->createNotification(
                $receiver_id,
                'Assign For Engineer Duty',
                'You are assigned as Rehlko Engineer.',
                'assign_engineer'
            );
            $report_subject = 'You are assigned as Rehlko Customer Care System Engineer';
                $emailBody = $this->mailer->getEmailTemplate('assign_engineer', [
                    'engineer_name' => $engineer['fullname'],
                ]);
                $this->mailer->sendMail($engineer['email'], $engineer['fullname'], $report_subject, $emailBody);
        }
        
    }
}
?>