<?php
// pages/users_logic.php

// Handle Actions
if (isset($_POST['add_user'])) {
    if (can('users_add')) {
        $username = $_POST['username'] ?? '';
        $password = $_POST['password'] ?? '';
        $email = $_POST['email'] ?? '';
        $phone = $_POST['phone'] ?? '';
        $group_id = (int)($_POST['group_id'] ?? 0) ?: null;
        $outlet_ids = $_POST['outlet_ids'] ?? [];
        
        if ($username && $password) {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $stmt = db()->prepare("INSERT INTO users (username, password, email, phone, group_id) VALUES (?, ?, ?, ?, ?)");
            try {
                $stmt->execute([$username, $hashed_password, $email, $phone, $group_id]);
                $user_id = db()->lastInsertId();
                
                if (!empty($outlet_ids)) {
                    $stmtOut = db()->prepare("INSERT INTO user_outlets (user_id, outlet_id) VALUES (?, ?)");
                    foreach ($outlet_ids as $oid) {
                        $stmtOut->execute([$user_id, $oid]);
                    }
                }
                
                $message = "User added successfully!";
            } catch (PDOException $e) {
                if ($e->getCode() == '23000') {
                    $message = "Error: Username already exists.";
                } else {
                    $message = "Error adding user: " . $e->getMessage();
                }
            }
        }
    }
}

if (isset($_POST['edit_user'])) {
    if (can('users_edit')) {
        $id = (int)$_POST['id'];
        $username = $_POST['username'] ?? '';
        $email = $_POST['email'] ?? '';
        $phone = $_POST['phone'] ?? '';
        $group_id = (int)($_POST['group_id'] ?? 0) ?: null;
        $status = $_POST['status'] ?? 'active';
        $outlet_ids = $_POST['outlet_ids'] ?? [];
        
        if ($id && $username) {
            $stmt = db()->prepare("UPDATE users SET username = ?, email = ?, phone = ?, group_id = ?, status = ? WHERE id = ?");
            $stmt->execute([$username, $email, $phone, $group_id, $status, $id]);
            
            if (!empty($_POST['password'])) {
                $hashed_password = password_hash($_POST['password'], PASSWORD_DEFAULT);
                $stmt = db()->prepare("UPDATE users SET password = ? WHERE id = ?");
                $stmt->execute([$hashed_password, $id]);
            }
            
            // Update Outlets
            db()->prepare("DELETE FROM user_outlets WHERE user_id = ?")->execute([$id]);
            if (!empty($outlet_ids)) {
                $stmtOut = db()->prepare("INSERT INTO user_outlets (user_id, outlet_id) VALUES (?, ?)");
                foreach ($outlet_ids as $oid) {
                    $stmtOut->execute([$id, $oid]);
                }
            }
            
            $message = "User updated successfully!";
        }
    }
}

if (isset($_POST['delete_user'])) {
    if (can('users_delete')) {
        $id = (int)$_POST['id'];
        if ($id) {
            $stmt = db()->prepare("DELETE FROM users WHERE id = ?");
            $stmt->execute([$id]);
            $message = "User deleted successfully!";
        }
    }
}

// Fetch Data
$page_num = isset($_GET['p']) ? max(1, (int)$_GET['p']) : 1;
$items_per_page = 20;
$offset = ($page_num - 1) * $items_per_page;

$total_users = db()->query("SELECT COUNT(*) FROM users")->fetchColumn();
$total_pages = ceil($total_users / $items_per_page);

$data['users'] = db()->query("
    SELECT u.*, g.name as group_name, GROUP_CONCAT(uo.outlet_id) as outlet_ids 
    FROM users u 
    LEFT JOIN role_groups g ON u.group_id = g.id 
    LEFT JOIN user_outlets uo ON u.id = uo.user_id 
    GROUP BY u.id 
    ORDER BY u.username ASC
    LIMIT $items_per_page OFFSET $offset
")->fetchAll();

$data['role_groups'] = db()->query("SELECT id, name FROM role_groups ORDER BY name ASC")->fetchAll();
$data['outlets'] = db()->query("SELECT * FROM outlets ORDER BY name ASC")->fetchAll();
$data['current_page'] = $page_num;
$data['total_pages'] = $total_pages;
