<?php
require_once 'Logger.php';

class Payroll {
    private $db;
    private $logger;

    public function __construct($db, $logger = null) {
        $this->db = $db;
        $this->logger = $logger;
    }

    public function register($employee_fullname, $date_of_birth, $employee_phone, $email, $home_district, $ta, $village, $place_of_residence, $national_id, $highest_qualification, $next_of_kin_fullname, $next_of_kin_phone, $next_of_kin_address, $employee_position, $basic_salary, $branch, $contract_start, $contract_ends, $payment_frequency, $bank_details, $id_copy, $certificates_copy) {
     //   $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        $sql = "INSERT INTO employee (employee_fullname, date_of_birth, employee_phone, email, home_district, ta, village, place_of_residence, national_id, highest_qualification, next_of_kin_fullname, next_of_kin_phone, next_of_kin_address, employee_position, basic_salary, branch, contract_start, contract_ends, payment_frequency, bank_details, id_copy, certificates_copy) VALUES (:employee_fullname, :date_of_birth, :employee_phone, :email, :home_district, :ta, :village, :place_of_residence, :national_id, :highest_qualification, :next_of_kin_fullname, :next_of_kin_phone, :next_of_kin_address, :employee_position, :basic_salary, :branch, :contract_start, :contract_ends, :payment_frequency, :bank_details, :id_copy, :certificates_copy)";
        $stmt = $this->db->prepare($sql);
  
  
		$stmt->bindParam(':employee_fullname', $employee_fullname);
        $stmt->bindParam(':date_of_birth', $date_of_birth);
        $stmt->bindParam(':employee_phone', $employee_phone);
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':home_district', $home_district);
		$stmt->bindParam(':ta', $ta);
        $stmt->bindParam(':village', $village);
        $stmt->bindParam(':place_of_residence', $place_of_residence);
        $stmt->bindParam(':national_id', $national_id);
        $stmt->bindParam(':highest_qualification', $highest_qualification);
		$stmt->bindParam(':next_of_kin_fullname', $next_of_kin_fullname);
        $stmt->bindParam(':next_of_kin_phone', $next_of_kin_phone);
        $stmt->bindParam(':next_of_kin_address', $next_of_kin_address);
        $stmt->bindParam(':employee_position', $employee_position);
        $stmt->bindParam(':basic_salary', $basic_salary);
        $stmt->bindParam(':branch', $branch);
		
		$stmt->bindParam(':contract_start', $contract_start);
		$stmt->bindParam(':contract_ends', $contract_ends);
		$stmt->bindParam(':payment_frequency', $payment_frequency);
		$stmt->bindParam(':bank_details', $bank_details);
		$stmt->bindParam(':id_copy', $id_copy);
		$stmt->bindParam(':certificates_copy', $certificates_copy);

        $result = $stmt->execute();

        if ($result && $this->logger) {
            $userId = $this->db->lastInsertId();

		/*           
		   $this->logger->logUser('CREATE', $userId, [
                'username' => $username,
                'role' => $role,
                'email' => $email,
                'branch_id' => $branch_id
            ]); */
        }

        return $result;
    }

    public function login($username, $password) {
        $sql = "SELECT * FROM users WHERE username = :username";
        $stmt = $this->db->prepare($sql);
        $stmt->bindParam(':username', $username);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user) {
            if (password_verify($password, $user['password'])) {
                return $user;
            } else {
                error_log("Password verification failed for username: $username");
            }
        } else {
            error_log("User not found: $username");
        }
        return false;
    }

    public function getEmployeeById($id) {
        $sql = "SELECT * FROM employee WHERE employee_id = :id";
        $stmt = $this->db->prepare($sql);
        $stmt->bindParam(':id', $id);
        $stmt->execute();
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function updateUser($id, $username, $password, $role, $email, $branch_id) {
        // Get old values for logging
        $oldUser = null;
        if ($this->logger) {
            $oldUser = $this->getUserById($id);
        }

        $query = "UPDATE users SET username = :username, role = :role, email = :email, branch_id = :branch_id";

        if (!empty($password)) {
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            $query .= ", password = :password";
        }

        $query .= " WHERE user_id = :id";

        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':username', $username);
        $stmt->bindParam(':role', $role);
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':branch_id', $branch_id);
        $stmt->bindParam(':id', $id);

        if (!empty($password)) {
            $stmt->bindParam(':password', $hashedPassword);
        }

        $result = $stmt->execute();

        if ($result && $this->logger && $oldUser) {
            $newValues = [
                'username' => $username,
                'role' => $role,
                'email' => $email,
                'branch_id' => $branch_id
            ];
            if (!empty($password)) {
                $newValues['password'] = '***CHANGED***';
            }

            $this->logger->logUser('UPDATE', $id, $newValues, $oldUser);
        }

        return $result;
    }


    public function deleteEmployee($id) {
        // Get user info for logging before deletion
        $userInfo = null;
        if ($this->logger) {
            $userInfo = $this->getEmployeeById($id);
        }

        $query = "DELETE FROM employee WHERE employee_id = :id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':id', $id);
        $result = $stmt->execute();

/*
        if ($result && $this->logger && $userInfo) {
            $this->logger->logUser('DELETE', $id, null, $userInfo);
        } */

        return $result;
    }



public function getStockTakingReport($sessionID, $itemStatus) {

    if ($itemStatus == 'missing') {

        //  Insert missing items (avoid duplicates)
       
       /*
        $insertQuery = "
            INSERT INTO missing_items (
                stock_session_id,
				item_id,
				unique_code,
                created_at
            )
            SELECT 
                stv.session_id,
				stv.item_id,
				stv.unique_code,
                 NOW()
            FROM stock_taking_verifications stv
            INNER JOIN items 
                ON stv.unique_code = items.unique_code
            WHERE stv.status = 'missing'
            AND stv.session_id = :sessionID
            AND NOT EXISTS (
                SELECT 1 FROM missing_items mi 
                WHERE mi.unique_code = stv.unique_code 
                AND mi.stock_session_id = stv.session_id
            )
        ";

        $stmt = $this->db->prepare($insertQuery);
        $stmt->bindParam(':sessionID', $sessionID);
        $stmt->execute();

       */
		
		 $query = "
            SELECT * 
            FROM stock_taking_verifications stv
            INNER JOIN items 
                ON stv.unique_code = items.unique_code
            WHERE stv.status = 'missing'
            AND stv.session_id = :sessionID
        ";

    } else if ($itemStatus == 'found') {

        $query = "
            SELECT * 
            FROM stock_taking_verifications stv
            INNER JOIN items 
                ON stv.unique_code = items.unique_code
            WHERE stv.status = 'found'
            AND stv.session_id = :sessionID
        ";

    } else {

        $query = "
            SELECT * 
            FROM stock_taking_verifications stv
            INNER JOIN items 
                ON stv.unique_code = items.unique_code
            WHERE stv.session_id = :sessionID
        ";
    }

    // Execute SELECT query
    $stmt = $this->db->prepare($query);
    $stmt->bindParam(':sessionID', $sessionID);
    $stmt->execute();

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}



	public function newGrade($grade_title, $basic_salary, $pension, $health_insurance, $house_allowance, $overtime, $other) {
		$sql = "INSERT INTO salary_grade (grade_title, basic_salary, pension, health_insurance, house_allowance, overtime, other) VALUES (:grade_title, :basic_salary, :pension, :health_insurance, :house_allowance, :overtime, :other)";
        $stmt = $this->db->prepare($sql);
  
  
		$stmt->bindParam(':grade_title', $grade_title);
        $stmt->bindParam(':basic_salary', $basic_salary);
        $stmt->bindParam(':pension', $pension);
        $stmt->bindParam(':health_insurance', $health_insurance);
        $stmt->bindParam(':house_allowance', $house_allowance);
		$stmt->bindParam(':overtime', $overtime);
        $stmt->bindParam(':other', $other);

        $result = $stmt->execute();

        if ($result && $this->logger) {
            $userId = $this->db->lastInsertId();

		/*           
		   $this->logger->logUser('CREATE', $userId, [
                'username' => $username,
                'role' => $role,
                'email' => $email,
                'branch_id' => $branch_id
            ]); */
        }

        return $result;
    }
	
	 public function getGradeById($id) {
        $sql = "SELECT * FROM salary_grade WHERE grade_id = :id";
        $stmt = $this->db->prepare($sql);
        $stmt->bindParam(':id', $id);
        $stmt->execute();
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }


	public function getSalaryGrade() {
        $query = "SELECT * FROM salary_grade";
        $stmt = $this->db->prepare($query);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
	
	 public function deleteGrade($id) {
        // Get user info for logging before deletion
        /*$userInfo = null;
        if ($this->logger) {
            $userInfo = $this->getEmployeeById($id);
        }*/

        $query = "DELETE FROM salary_grade WHERE grade_id = :id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':id', $id);
        $result = $stmt->execute();

/*
        if ($result && $this->logger && $userInfo) {
            $this->logger->logUser('DELETE', $id, null, $userInfo);
        } */

        return $result;
    }




    public function updateGrade($grade_id, $grade_title, $basic_salary, $pension, $health_insurance, $house_allowance,$other) {
        $query = "UPDATE salary_grade SET grade_title = :grade_title, basic_salary = :basic_salary, pension = :pension, health_insurance = :health_insurance, house_allowance = :house_allowance , other = :other  WHERE grade_id = :id";

        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':grade_title', $grade_title);
        $stmt->bindParam(':basic_salary', $basic_salary);
        $stmt->bindParam(':pension', $pension);
        $stmt->bindParam(':health_insurance', $health_insurance);
        $stmt->bindParam(':house_allowance', $house_allowance);
		$stmt->bindParam(':other', $other);
		$stmt->bindParam(':id', $grade_id);
        $result = $stmt->execute();
		/*
        if ($result && $this->logger && $oldUser) {
            $newValues = [
                'username' => $username,
                'role' => $role,
                'email' => $email,
                'branch_id' => $branch_id
            ];*/
           

           // $this->logger->logUser('UPDATE', $id, $newValues, $oldUser);
        
        return $result;
    }





    public function getUserBranch($userId) {
        $query = "SELECT branch_id FROM users WHERE user_id = :user_id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':user_id', $userId);
        $stmt->execute();
        return $stmt->fetchColumn();
    }
	
	
	
	
	

    public function isUserInBranch($userId, $branchId) {
        $query = "SELECT COUNT(*) FROM users WHERE user_id = :user_id AND branch_id = :branch_id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':user_id', $userId);
        $stmt->bindParam(':branch_id', $branchId);
        $stmt->execute();
        return $stmt->fetchColumn() > 0;
    }
	
	public function newLoan($employee_id, $loan_type, $loan_amount, $interest_rate, $loan_months, $loans_starts, $loan_status) {
		$loan_date = date("Y-m-d");
	
		$sql = "INSERT INTO employee_loans (loan_date, employee_id, loan_type, loan_amount, interest_rate, loan_months, loans_starts, loan_status) VALUES (:loan_date, :employee_id, :loan_type, :loan_amount, :interest_rate, :loan_months, :loans_starts, :loan_status)";
        $stmt = $this->db->prepare($sql);
  
  
		$stmt->bindParam(':employee_id', $employee_id);
        $stmt->bindParam(':loan_type', $loan_type);
		$stmt->bindParam(':loan_date', $loan_date);
		
		
        $stmt->bindParam(':loan_amount', $loan_amount);
        $stmt->bindParam(':interest_rate', $interest_rate);
        $stmt->bindParam(':loan_months', $loan_months);
		$stmt->bindParam(':loans_starts', $loans_starts);
		$stmt->bindParam(':loan_status', $loan_status);
		
		

        $result = $stmt->execute();

        if ($result && $this->logger) {
            $userId = $this->db->lastInsertId();

		/*           
		   $this->logger->logUser('CREATE', $userId, [
                'username' => $username,
                'role' => $role,
                'email' => $email,
                'branch_id' => $branch_id
            ]); */
        }

        return $result;
    }
	
	 public function getLoans() {
        $query = "SELECT * FROM employee_loans";
        $stmt = $this->db->prepare($query);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
	
	 public function getLoansByID($id) {
        $query = "SELECT * FROM employee_loans INNER JOIN employee ON employee.employee_id=employee_loans.employee_id WHERE employee_loans.record_id=:id";
        $stmt = $this->db->prepare($query);
		$stmt->bindParam(':id', $id);
        $stmt->execute();
		
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
	
	
	
	
	
}
?>