<?php
class AuthController {
    private $conn;

    public function __construct($db) {
        $this->conn = $db;
    }

    public function login() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $email = $_POST['email'];
            $password = $_POST['password'];

            $stmt = $this->conn->prepare("SELECT id, password, name, status FROM users WHERE email = ?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows === 1) {
                $user = $result->fetch_assoc();
                if (password_verify($password, $user['password'])) {
                    if ($user['status'] == 'inactive') {
                         setFlash('error', 'Your account is inactive. Contact Admin.');
                    } else {
                        $_SESSION['user_id'] = $user['id'];
                        $_SESSION['user_name'] = $user['name'];
                        header("Location: " . BASE_URL . "?page=user&action=dashboard");
                        exit;
                    }
                } else {
                    setFlash('error', 'Invalid password.');
                }
            } else {
                setFlash('error', 'User not found.');
            }
        }
        require_once 'views/login.php';
    }

    public function adminLogin() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $username = $_POST['username'];
            $password = $_POST['password'];

            $stmt = $this->conn->prepare("SELECT id, password FROM admins WHERE username = ?");
            $stmt->bind_param("s", $username);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows === 1) {
                $admin = $result->fetch_assoc();
                // For simplicity, checking hash, but if we inserted plain text/dummy hash in setup,
                // we should ensure it matches.
                // The setup inserted a bcrypt hash for 'admin123'.
                if (password_verify($password, $admin['password'])) {
                    $_SESSION['admin_id'] = $admin['id'];
                    header("Location: " . BASE_URL . "?page=admin&action=dashboard");
                    exit;
                } else {
                    setFlash('error', 'Invalid Admin password.');
                }
            } else {
                setFlash('error', 'Admin not found.');
            }
        }
        require_once 'views/admin/login.php';
    }

    public function register() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $name = $_POST['name'];
            $email = $_POST['email'];
            $mobile = $_POST['mobile'];
            $password = password_hash($_POST['password'], PASSWORD_BCRYPT);

            // APIs
            $wa_url = $_POST['wa_url'];
            $wa_token = $_POST['wa_token'];
            $wa_instance = $_POST['wa_instance'];
            $sms_url = $_POST['sms_url'];
            $sms_key = $_POST['sms_key'];

            // Template Upload
            $target_dir = "uploads/templates/";
            if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);

            $file_name = time() . '_' . basename($_FILES["template_image"]["name"]);
            $target_file = $target_dir . $file_name;
            $uploadOk = 1;

            $check = getimagesize($_FILES["template_image"]["tmp_name"]);
            if($check === false) {
                setFlash('error', 'File is not an image.');
                $uploadOk = 0;
            }

            if ($uploadOk && move_uploaded_file($_FILES["template_image"]["tmp_name"], $target_file)) {

                $this->conn->begin_transaction();

                try {
                    // Insert User
                    $stmt = $this->conn->prepare("INSERT INTO users (name, email, mobile, password) VALUES (?, ?, ?, ?)");
                    $stmt->bind_param("ssss", $name, $email, $mobile, $password);
                    $stmt->execute();
                    $user_id = $this->conn->insert_id;

                    // Insert APIs
                    $stmt_api = $this->conn->prepare("INSERT INTO user_apis (user_id, wa_url, wa_token, wa_instance_id, sms_api_url, sms_api_key) VALUES (?, ?, ?, ?, ?, ?)");
                    $stmt_api->bind_param("isssss", $user_id, $wa_url, $wa_token, $wa_instance, $sms_url, $sms_key);
                    $stmt_api->execute();

                    // Insert Template
                    $stmt_tpl = $this->conn->prepare("INSERT INTO user_templates (user_id, image_path) VALUES (?, ?)");
                    $stmt_tpl->bind_param("is", $user_id, $target_file);
                    $stmt_tpl->execute();

                    $this->conn->commit();
                    setFlash('success', 'Registration successful! Please login.');
                    header("Location: " . BASE_URL . "?page=auth&action=login");
                    exit;

                } catch (Exception $e) {
                    $this->conn->rollback();
                    setFlash('error', 'Registration failed: ' . $e->getMessage());
                }

            } else {
                setFlash('error', 'Sorry, there was an error uploading your file.');
            }
        }
        require_once 'views/register.php';
    }

    public function logout() {
        session_destroy();
        header("Location: " . BASE_URL . "?page=auth&action=login");
        exit;
    }
}
?>
