<?php
class AdminController {
    private $conn;

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

    public function dashboard() {
        $result = $this->conn->query("SELECT * FROM users ORDER BY created_at DESC");
        $users = [];
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $users[] = $row;
            }
        }
        require_once 'views/admin/dashboard.php';
    }

    public function activateUser() {
        if (isset($_GET['id'])) {
            $id = intval($_GET['id']);
            $this->conn->query("UPDATE users SET status='active' WHERE id=$id");
            setFlash('success', 'User activated successfully.');
        }
        header("Location: " . BASE_URL . "?page=admin&action=dashboard");
    }

    public function deactivateUser() {
        if (isset($_GET['id'])) {
            $id = intval($_GET['id']);
            $this->conn->query("UPDATE users SET status='inactive' WHERE id=$id");
            setFlash('success', 'User deactivated successfully.');
        }
        header("Location: " . BASE_URL . "?page=admin&action=dashboard");
    }

    public function deleteUser() {
        if (isset($_GET['id'])) {
            $id = intval($_GET['id']);
            // Database schema has ON DELETE CASCADE for related tables, so just deleting user is enough.
            if ($this->conn->query("DELETE FROM users WHERE id=$id")) {
                setFlash('error', 'User deleted successfully.'); // Using error style for delete notification
            } else {
                setFlash('error', 'Failed to delete user.');
            }
        }
        header("Location: " . BASE_URL . "?page=admin&action=dashboard");
    }

    public function addUser() {
        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_apikey = $_POST['wa_apikey'];

            $sms_url = $_POST['sms_url'];
            $sms_user = $_POST['sms_user'];
            $sms_password = $_POST['sms_password'];
            $sms_sender_id = $_POST['sms_sender_id'];

            // Greeting Text
            $greeting_text = $_POST['greeting_text'];

            // Template Upload
            $target_dir = "uploads/templates/";
            // Ensure dir exists
            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, status) VALUES (?, ?, ?, ?, 'active')");
                    $stmt->bind_param("ssss", $name, $email, $mobile, $password);
                    $stmt->execute();
                    $user_id = $this->conn->insert_id;

                    // Insert APIs (Updated Schema)
                    $stmt_api = $this->conn->prepare("INSERT INTO user_apis (user_id, wa_url, wa_apikey, sms_api_url, sms_user, sms_password, sms_sender_id) VALUES (?, ?, ?, ?, ?, ?, ?)");
                    $stmt_api->bind_param("issssss", $user_id, $wa_url, $wa_apikey, $sms_url, $sms_user, $sms_password, $sms_sender_id);
                    $stmt_api->execute();

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

                    $this->conn->commit();
                    setFlash('success', 'User added successfully!');
                    header("Location: " . BASE_URL . "?page=admin&action=dashboard");
                    exit;

                } catch (Exception $e) {
                    $this->conn->rollback();
                    setFlash('error', 'Failed to add user: ' . $e->getMessage());
                }

            } else {
                setFlash('error', 'Error uploading file.');
            }
        }
        require_once 'views/admin/add_user.php';
    }

    public function editUser() {
        if (!isset($_GET['id'])) {
            header("Location: " . BASE_URL . "?page=admin&action=dashboard");
            exit;
        }

        $id = intval($_GET['id']);

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $name = $_POST['name'];
            $email = $_POST['email'];
            $mobile = $_POST['mobile'];
            // Password update only if provided
            $password = !empty($_POST['password']) ? password_hash($_POST['password'], PASSWORD_BCRYPT) : null;

            // APIs
            $wa_url = $_POST['wa_url'];
            $wa_apikey = $_POST['wa_apikey'];

            $sms_url = $_POST['sms_url'];
            $sms_user = $_POST['sms_user'];
            $sms_password = $_POST['sms_password'];
            $sms_sender_id = $_POST['sms_sender_id'];

            // Greeting Text & Settings
            $greeting_text = $_POST['greeting_text'];
            $pos_x = intval($_POST['pos_x']);
            $pos_y = intval($_POST['pos_y']);
            $font_size = intval($_POST['font_size']);
            $font_color = $_POST['font_color'];

            // Template Upload
            $target_dir = "uploads/templates/";
            // Ensure dir exists
            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;
            $newImage = false;

            if (!empty($_FILES["template_image"]["name"])) {
                $check = getimagesize($_FILES["template_image"]["tmp_name"]);
                if($check === false) {
                    setFlash('error', 'File is not an image.');
                    $uploadOk = 0;
                } else {
                    if (move_uploaded_file($_FILES["template_image"]["tmp_name"], $target_file)) {
                        $newImage = true;
                    } else {
                        setFlash('error', 'Error uploading file.');
                        $uploadOk = 0;
                    }
                }
            }

            if ($uploadOk) {
                $this->conn->begin_transaction();
                try {
                    // Update User
                    $sqlUser = "UPDATE users SET name=?, email=?, mobile=?";
                    if ($password) $sqlUser .= ", password=?";
                    $sqlUser .= " WHERE id=?";

                    $stmt = $this->conn->prepare($sqlUser);
                    if ($password) {
                        $stmt->bind_param("ssssi", $name, $email, $mobile, $password, $id);
                    } else {
                        $stmt->bind_param("sssi", $name, $email, $mobile, $id);
                    }
                    $stmt->execute();

                    // Update APIs
                    $stmt_api = $this->conn->prepare("UPDATE user_apis SET wa_url=?, wa_apikey=?, sms_api_url=?, sms_user=?, sms_password=?, sms_sender_id=? WHERE user_id=?");
                    $stmt_api->bind_param("ssssssi", $wa_url, $wa_apikey, $sms_url, $sms_user, $sms_password, $sms_sender_id, $id);
                    $stmt_api->execute();

                    // Update Template
                    // Update Template
                    if ($newImage) {
                         $stmt_tpl = $this->conn->prepare("UPDATE user_templates SET image_path=?, greeting_text=?, pos_x=?, pos_y=?, font_size=?, font_color=? WHERE user_id=?");
                         $stmt_tpl->bind_param("ssiiisi", $target_file, $greeting_text, $pos_x, $pos_y, $font_size, $font_color, $id);
                    } else {
                         $stmt_tpl = $this->conn->prepare("UPDATE user_templates SET greeting_text=?, pos_x=?, pos_y=?, font_size=?, font_color=? WHERE user_id=?");
                         $stmt_tpl->bind_param("siiisi", $greeting_text, $pos_x, $pos_y, $font_size, $font_color, $id);
                    }
                    $stmt_tpl->execute();

                    $this->conn->commit();
                    setFlash('success', 'User updated successfully!');
                    header("Location: " . BASE_URL . "?page=admin&action=dashboard");
                    exit;

                } catch (Exception $e) {
                    $this->conn->rollback();
                    setFlash('error', 'Failed to update user: ' . $e->getMessage());
                }
            }
        }

        // Fetch User Data for Edit View
        $stmt = $this->conn->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();

        if (!$user) {
            setFlash('error', 'User not found.');
            header("Location: " . BASE_URL . "?page=admin&action=dashboard");
            exit;
        }

        $stmtApi = $this->conn->prepare("SELECT * FROM user_apis WHERE user_id = ?");
        $stmtApi->bind_param("i", $id);
        $stmtApi->execute();
        $api = $stmtApi->get_result()->fetch_assoc();

        $stmtTpl = $this->conn->prepare("SELECT * FROM user_templates WHERE user_id = ?");
        $stmtTpl->bind_param("i", $id);
        $stmtTpl->execute();
        $template = $stmtTpl->get_result()->fetch_assoc();

        require_once 'views/admin/edit_user.php';
    }

    public function users() {
        $this->dashboard();
    }
}
?>
