<?php

namespace App\Controllers;

use Core\Request;
use Core\Redirect;
use Core\DB;

class Auth
{

    public function loginProcess()
    {
        $username = Request::getPost('username', 'string');
        $password = Request::getPost('password', 'string');

        if (empty($username) || empty($password)) {
            Redirect::redirectError('login', 'Please fill in all the fields');
        }

        // Get database connection
        $db = new DB();
        $conn = $db->getConnection();

        //Check db is connected
        if ($conn->connect_error) {
            Redirect::redirectError('login', 'Database connection failed: ' . $conn->connect_error);
        }
        // Prepare and bind
        $stmt = $conn->prepare("SELECT * FROM system_user WHERE username = ?");
        if ($stmt === false) {
            Redirect::redirectError('login', 'Database query preparation failed: ' . $conn->error);
        }
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result->fetch_assoc();
        if ($user) {
            if (password_verify($password, $user['password'])) {
                session_start();
                $_SESSION['user'] = $user;
                Redirect::redirectSuccess('dashboard', 'Login successful');
            } else {
                Redirect::redirectError('login', 'Invalid password');
            }
        } else {
            Redirect::redirectError('login', 'User does not exist');
        }
    }


    public function changePasswordProcess()
    {
        $username = Request::getPost('username', 'string');
        $user_id =  Request::getPost('user_id', 'int');
        $new_password = Request::getPost('new_password', 'string');
        $confirm_new_password = Request::getPost('confirm_new_password', 'string');

        if (empty($username)) {
            Redirect::redirectError('change_password', 'Please provide a username');
        }

        // Get database connection
        $db = new DB();
        $conn = $db->getConnection();
        if ($conn->connect_error) {
            Redirect::redirectError('change_password', 'Database connection failed: ' . $conn->connect_error);
        }

        // Check if the user exists
        $stmtCheck = $conn->prepare("SELECT * FROM system_user WHERE id = ?");
        if ($stmtCheck === false) {
            Redirect::redirectError('change_password', 'Database query preparation failed: ' . $conn->error);
        }
        $stmtCheck->bind_param("i", $user_id);
        $stmtCheck->execute();
        $resultCheck = $stmtCheck->get_result();
        $userCheck = $resultCheck->fetch_assoc();

        if ($userCheck) {
            // Prepare update query
            if (!empty($new_password) && !empty($confirm_new_password)) {
                if ($new_password !== $confirm_new_password) {
                    Redirect::redirectError('change_password', 'New password and confirm new password do not match');
                }
                $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                $stmtUpdate = $conn->prepare("UPDATE system_user SET username = ?, password = ? WHERE id = ?");
                $stmtUpdate->bind_param("ssi", $username, $hashed_password, $user_id);
            } else {
                $stmtUpdate = $conn->prepare("UPDATE system_user SET username = ? WHERE id = ?");
                $stmtUpdate->bind_param("si", $username, $user_id);
            }

            if ($stmtUpdate === false) {
                Redirect::redirectError('change_password', 'Database query preparation failed: ' . $conn->error);
            }

            if ($stmtUpdate->execute()) {
                //delete old session
                session_destroy();
                unset($_SESSION['user']);
                // Start a new session
                session_start();
                // Set the new session variable
                $_SESSION['user'] = [
                    'id' => $user_id,
                    'username' => $username,
                    'password' => $hashed_password
                ];
                Redirect::redirectSuccess('dashboard', 'Username and password updated successfully');
            } else {
                Redirect::redirectError('change_password', 'Failed to update credentials: ' . $stmtUpdate->error);
            }
        } else {
            Redirect::redirectError('change_password', 'User does not exist');
        }
    }



    public function logout()
    {
        session_start();
        // Unset all session variables
        $_SESSION = array();

        // Destroy the session
        session_destroy();

        // Redirect to login page
        Redirect::redirectSuccess('login', 'Logout successful');
    }
}
