<?php
/**
 * User Class
 * Handles user operations
 */

require_once __DIR__ . '/Database.php';

class User {
    private $db;

    public function __construct() {
        $this->db = Database::getInstance();
    }

    /**
     * Get user by ID
     */
    public function getUserById($userId) {
        return $this->db->fetchOne(
            "SELECT * FROM users WHERE id = ?",
            [$userId]
        );
    }

    /**
     * Get user by email
     */
    public function getUserByEmail($email) {
        return $this->db->fetchOne(
            "SELECT * FROM users WHERE email = ?",
            [$email]
        );
    }

    /**
     * Update user (alias for updateProfile for consistency)
     */
    public function updateUser($userId, $data) {
        return $this->updateProfile($userId, $data);
    }

    /**
     * Update user profile
     */
    public function updateProfile($userId, $data) {
        $fields = [];
        $params = [];

        $allowedFields = ['first_name', 'last_name', 'email', 'phone', 'cnp', 'company_name', 
                         'cui', 'reg_com', 'bank_account', 'default_order_type', 'password'];

        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $fields[] = "{$field} = ?";
                $params[] = $data[$field];
            }
        }

        if (empty($fields)) {
            return false;
        }

        $params[] = $userId;
        $sql = "UPDATE users SET " . implode(', ', $fields) . ", updated_at = NOW() WHERE id = ?";
        
        return $this->db->execute($sql, $params);
    }

    /**
     * Change password
     */
    public function changePassword($userId, $oldPassword, $newPassword) {
        $user = $this->getUserById($userId);
        
        if (!$user || !password_verify($oldPassword, $user['password'])) {
            return false;
        }

        $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
        return $this->db->execute(
            "UPDATE users SET password = ? WHERE id = ?",
            [$hashedPassword, $userId]
        );
    }

    /**
     * Add loyalty points
     */
    public function addLoyaltyPoints($userId, $points, $orderId = null, $description = null) {
        $this->db->beginTransaction();
        
        try {
            // Update user points
            $this->db->execute(
                "UPDATE users SET loyalty_points = loyalty_points + ? WHERE id = ?",
                [$points, $userId]
            );

            // Log points
            $this->db->execute(
                "INSERT INTO loyalty_points (user_id, points, type, order_id, description) 
                 VALUES (?, ?, 'earned', ?, ?)",
                [$userId, $points, $orderId, $description]
            );

            $this->db->commit();
            return true;
        } catch (Exception $e) {
            $this->db->rollback();
            return false;
        }
    }

    /**
     * Use loyalty points
     */
    public function useLoyaltyPoints($userId, $points, $orderId = null) {
        $user = $this->getUserById($userId);
        
        if (!$user || $user['loyalty_points'] < $points) {
            return false;
        }

        $this->db->beginTransaction();
        
        try {
            // Update user points
            $this->db->execute(
                "UPDATE users SET loyalty_points = loyalty_points - ? WHERE id = ?",
                [$points, $userId]
            );

            // Log points usage
            $this->db->execute(
                "INSERT INTO loyalty_points (user_id, points, type, order_id, description) 
                 VALUES (?, ?, 'used', ?, 'Points used for order discount')",
                [$userId, $points, $orderId]
            );

            $this->db->commit();
            return true;
        } catch (Exception $e) {
            $this->db->rollback();
            return false;
        }
    }

    /**
     * Get user B2B group
     */
    public function getB2BGroup($userId) {
        return $this->db->fetchOne(
            "SELECT bg.* FROM b2b_groups bg
             INNER JOIN b2b_group_users bgu ON bg.id = bgu.b2b_group_id
             WHERE bgu.user_id = ? AND bg.is_active = 1",
            [$userId]
        );
    }

    /**
     * Get user addresses
     */
    public function getAddresses($userId, $type = null) {
        // Type parameter kept for backward compatibility but not used in query
        $sql = "SELECT * FROM addresses WHERE user_id = ? ORDER BY is_default DESC, created_at DESC";
        return $this->db->fetchAll($sql, [$userId]);
    }

    /**
     * Get user addresses (alias for getAddresses)
     */
    public function getUserAddresses($userId) {
        return $this->getAddresses($userId);
    }

    /**
     * Get address by ID
     */
    public function getAddressById($addressId) {
        return $this->db->fetchOne(
            "SELECT * FROM addresses WHERE id = ?",
            [$addressId]
        );
    }

    /**
     * Add address
     */
    public function addAddress($userId, $data) {
        $sql = "INSERT INTO addresses (user_id, first_name, last_name, email, phone, company_name, 
                cui, reg_com, country, county, city, postcode, address_line1, address_line2, is_default) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $params = [
            $userId,
            $data['first_name'] ?? null,
            $data['last_name'] ?? null,
            $data['email'] ?? null,
            $data['phone'] ?? null,
            $data['company_name'] ?? null,
            $data['cui'] ?? null,
            $data['reg_com'] ?? null,
            $data['country'] ?? 'Romania',
            $data['county'] ?? null,
            $data['city'] ?? null,
            $data['postcode'] ?? $data['postal_code'] ?? null,
            $data['address_line1'] ?? null,
            $data['address_line2'] ?? null,
            $data['is_default'] ?? 0
        ];

        // If this is default, unset other defaults
        if (($data['is_default'] ?? 0) == 1) {
            $this->db->execute(
                "UPDATE addresses SET is_default = 0 WHERE user_id = ?",
                [$userId]
            );
        }

        $this->db->execute($sql, $params);
        return $this->db->lastInsertId();
    }

    /**
     * Update address
     */
    public function updateAddress($addressId, $userId, $data) {
        // Verify address belongs to user
        $address = $this->getAddressById($addressId);
        if (!$address || $address['user_id'] != $userId) {
            return false;
        }

        // If setting as default, unset other defaults
        if (($data['is_default'] ?? 0) == 1) {
            $this->db->execute(
                "UPDATE addresses SET is_default = 0 WHERE user_id = ?",
                [$userId]
            );
        }

        $fields = [];
        $params = [];

        $allowedFields = ['first_name', 'last_name', 'email', 'phone', 'company_name', 
                         'cui', 'reg_com', 'address_line1', 'address_line2', 'city', 
                         'county', 'postcode', 'country', 'is_default'];

        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $fields[] = "{$field} = ?";
                $params[] = $data[$field];
            } elseif (isset($data['postal_code']) && $field === 'postcode') {
                // Support both postcode and postal_code for backward compatibility
                $fields[] = "postcode = ?";
                $params[] = $data['postal_code'];
            }
        }

        if (empty($fields)) {
            return false;
        }

        $params[] = $addressId;
        $sql = "UPDATE addresses SET " . implode(', ', $fields) . ", updated_at = NOW() WHERE id = ?";
        
        return $this->db->execute($sql, $params);
    }

    /**
     * Delete address
     */
    public function deleteAddress($addressId, $userId) {
        // Verify address belongs to user
        $address = $this->getAddressById($addressId);
        if (!$address || $address['user_id'] != $userId) {
            return false;
        }

        return $this->db->execute(
            "DELETE FROM addresses WHERE id = ? AND user_id = ?",
            [$addressId, $userId]
        );
    }
}
?>

