<?php
require_once __DIR__ . '/../config/Database.php';

class User {
    private $db;
    private $conn;
    
    public function __construct() {
        $this->db = new Database();
        $this->conn = $this->db->getConnection();
    }
    
    public function authenticate($userId, $pin) {
        $query = "SELECT * FROM users WHERE id = ? AND status = 'active'";
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("s", $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $user = $result->fetch_assoc();
            // For production, use password_verify() with hashed passwords
            if ($user['pin'] == md5($pin) || password_verify($pin, $user['pin']) || $user['pin'] === $pin) {
                return [
                    'success' => true,
                    'user' => [
                        'id' => $user['id'],
                        'name' => $user['name'],
                        'role' => $user['role'],
                        'email' => $user['email']
                    ]
                ];
            }
        }
        return ['success' => false, 'message' => 'Invalid credentials'];
    }
    
    public function getUser($userId) {
        $query = "SELECT id, name, role, email, phone, status, created_at FROM users WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("s", $userId);
        $stmt->execute();
        return $stmt->get_result()->fetch_assoc();
    }
    
    public function getAllUsers() {
        $query = "SELECT id, name, role, email, phone, status, created_at FROM users WHERE status = 'active' ORDER BY name";
        $result = $this->conn->query($query);
        return $result->fetch_all(MYSQLI_ASSOC);
    }
    
    public function createUser($data) {
        $query = "INSERT INTO users (id, name, role, pin, email, phone) VALUES (?, ?, ?, ?, ?, ?)";
        $stmt = $this->conn->prepare($query);
        $hashedPin = md5($data['pin']);
        $stmt->bind_param("ssssss", $data['id'], $data['name'], $data['role'], $hashedPin, $data['email'], $data['phone']);
        return $stmt->execute();
    }

    public function updateUserPin($userId, $pin) {
        $query = "UPDATE users SET pin = ? WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $hashedPin = md5($pin);
        $stmt->bind_param("ss", $hashedPin, $userId);
        return $stmt->execute();
    }

    public function updateUserProfile($userId, $data) {
        $fields = [];
        $types = '';
        $values = [];

        if (!empty($data['name'])) {
            $fields[] = 'name = ?';
            $types .= 's';
            $values[] = $data['name'];
        }
        if (isset($data['email'])) {
            $fields[] = 'email = ?';
            $types .= 's';
            $values[] = $data['email'];
        }
        if (isset($data['phone'])) {
            $fields[] = 'phone = ?';
            $types .= 's';
            $values[] = $data['phone'];
        }
        if (isset($data['role'])) {
            $fields[] = 'role = ?';
            $types .= 's';
            $values[] = $data['role'];
        }

        if (empty($fields)) return false;

        $query = "UPDATE users SET " . implode(', ', $fields) . " WHERE id = ?";
        $types .= 's';
        $values[] = $userId;

        $stmt = $this->conn->prepare($query);
        $stmt->bind_param($types, ...$values);
        return $stmt->execute();
    }

    public function deleteUserSoft($userId) {
        // Soft delete to preserve sales data
        $query = "UPDATE users SET status = 'inactive' WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("s", $userId);
        return $stmt->execute();
    }
}
?>
